How to decode JSON in Flutter?

JsonFlutterParsingDartDecode

Json Problem Overview


How to decode JSON in Flutter?

The question is simple, but the answer isn't, at least for me.

I have a project that uses a lot of JSON Strings. Basically, the entire communication between the app and the server is through JSON.

I have been using JSON.decode(json_string) to deal with it, but today I updated the Flutter core (0.5.8-pre.178) and JSON.decode isn't available anymore.

I went to the Flutter Docs to seek help, but it still says to use JSON.decode.

So, how to decode JSON in Flutter from now on?

Json Solutions


Solution 1 - Json

You will need to import dart:convert:

import 'dart:convert';

Inline example

String rawJson = '{"name":"Mary","age":30}';

Map<String, dynamic> map = jsonDecode(rawJson); // import 'dart:convert';

String name = map['name'];
int age = map['age'];

Person person = Person(name, age);

Note: When I was doing this in VS Code for server side Dart I had to specify the type:

Map<String, dynamic> map = jsonDecode(rawJson) as Map<String, dynamic>;

Model class example

The model class includes the map conversion logic:

class Person {
  String name;
  int age;
  Person(this.name, this.age);

  // named constructor
  Person.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        age = json['age'];

  // method
  Map<String, dynamic> toJson() {
    return {
      'name': name,
      'age': age,
    };
  }
 
}

And the JSON conversion is done like this:

String rawJson = '{"name":"Mary","age":30}';
Map<String, dynamic> map = jsonDecode(rawJson);
Person person = Person.fromJson(map);

See my full answer here.

Generating the serialization code

It is easy to make errors when writing the serialization code, so it is generally recommended to use the json_serializable package by the Dart Team. However, you can read about the pros and cons of the different methods here.

If you want even more options you can also check out the built_value package.

See also

Solution 2 - Json

Just use

json.decode()

or

jsonDecode()

In Dart 2 all screaming-case constants were changed to lower-camel-case.

Ensure to import 'dart:convert';

Solution 3 - Json

You need to use import 'dart:convert';

> Decode : JsonDecoder().convert("$response"); > > Encode : JsonEncoder().convert(object)

Solution 4 - Json

For decode a Json like this

{
"id":"xx888as88",
"timestamp":"2020-08-18 12:05:40",
"sensors":[
    {
     "name":"Gyroscope",
     "values":[
         {
          "type":"X",
          "value":-3.752716,
          "unit":"r/s"
         },
         {
           "type":"Y",
           "value":1.369709,
           "unit":"r/s"
         },
         {
           "type":"Z",
           "value":-13.085,
           "unit":"r/s"
         }
       ]
    }
  ]
}

I do this:

void setReceivedText(String text) {
    Map<String, dynamic> jsonInput = jsonDecode(text);
    
    _receivedText = 'ID: ' + jsonInput['id'] + '\n';
    _receivedText += 'Date: ' +jsonInput['timestamp']+ '\n';
    _receivedText += 'Device: ' +jsonInput['sensors'][0]['name'] + '\n';
    _receivedText += 'Type: ' +jsonInput['sensors'][0]['values'][0]['type'] + '\n';
    _receivedText += 'Value: ' +jsonInput['sensors'][0]['values'][0]['value'].toString() + '\n';
    _receivedText += 'Type: ' +jsonInput['sensors'][0]['values'][1]['type'] + '\n';
    _receivedText += 'Value: ' +jsonInput['sensors'][0]['values'][1]['value'].toString() + '\n';
    _receivedText += 'Type: ' +jsonInput['sensors'][0]['values'][2]['type'] + '\n';
    _receivedText += 'Value: ' +jsonInput['sensors'][0]['values'][2]['value'].toString();
     _historyText = '\n' + _receivedText;
}

Im new in Flutter so, work for me just now

Solution 5 - Json

There are a few different ways that you can parse the JSON code. Here are two small examples of them: JSON is just a text format that most REST APIs use to return their data.

Dart has built-in support for parsing JSON. Given a String you can use the dart:convertlibrary and convert the JSON (if valid JSON) to a Map with string keys and dynamic objects. You can parse JSON directly and use the map or you can parse it and put it into a typed object so that your data has more structure and it's easier to maintain.

Suppose that we need to parse this JSON data:

final jsonData = {
  "name": "John",
  "age": 20
}

Note: Use json.decode(jsonData) to turn the JSON string into a map.

Direct Parsing and Usage:

You can parse a JSON string by hand by using the dart:convert library.

var parsedJson = json.decode(jsonData);
print('${parsedJson.runtimeType} : $parsedJson');

//The code above will give you
_InternalLinkedHashMap<String, dynamic> : {name: John, age: 20}

So the way you access your parsed data is by using the key index on the returned map. Let’s index into the map and get the name and the age out.

import 'dart:convert';

void testParseJsonDirect() {
  var name = parsedJson['name'];
  var age = parsedJson['age'];
  print('$name is $age');
}

This doesn’t look too hard, but if you start working with complex JSON strings, it becomes very tedious to write and maintain.

Parse JSON Object

We create a Student class and do the parsing, pass the decoded JSON to the factory constructor:

class Student {
  final String name;
  final int age;

  Student({this.name, this.age});

  factory Student.fromJson(Map<String, dynamic> json) {
    return Student(name: json['name'], age: json['age']);
  }

  // Override toString to have a beautiful log of student object
  @override
  String toString() {
    return 'Student: {name = $name, age = $age}';
  }
}

Use dart:convert to parse the JSON. Here I use “raw string” to represent the JSON text. If you don’t know about “raw string”, you can checkpoint 4 and point 5 in String in Dart/Flutter – Things you should know.

void testParseJsonObject() {
  final jsonString = r'''
      {
        "name": "John",
        "age": 20
      }
  ''';

  // Use jsonDecode function to decode the JSON string
  // I assume the JSON format is correct 
  final json = jsonDecode(jsonString);
  final student = Student.fromJson(json);

  print(student);
}

Test it

void main(List<String> args) {
  testParseJsonObject();
}

// Output
Student: {name = John, age = 20}

Ans from: https://coflutter.com/dart-flutter-how-to-parse-json/

Solution 6 - Json

You can decode JSON strings, lists and maps directly to objects or to list of objects.

This is possible with package json_helpers.

import 'package:json_helpers/json_helpers.dart';

For example, you can convert the String result of a request (request.body) directly to a list of objects without too much trouble by calling just one method.

Detailed examples:

String to Post

  final text = '{"title": "Hello"}';
  final post = text.json((e) => Post.fromJson(e));
  print(post.title);

String to List<Post>

  final text = '[{"title": "Hello"}, {"title": "Goodbye"}]';
  final post = text.jsonList((e) => Post.fromJson(e));
  print(post[0].title);

Map to Post

  final map = {"title": "Hello"};
  final post = map.json((e) => Post.fromJson(e));
  print(post.title);

List<Map> to List<Post>

  final list = [{"title": "Hello"}, {"title": "Goodbye"}];
  final post = list.json((e) => Post.fromJson(e));
  print(post[0].title);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNotherosView Question on Stackoverflow
Solution 1 - JsonSuragchView Answer on Stackoverflow
Solution 2 - JsonGünter ZöchbauerView Answer on Stackoverflow
Solution 3 - JsonSanjayrajsinhView Answer on Stackoverflow
Solution 4 - JsonRDR_DevView Answer on Stackoverflow
Solution 5 - JsonParesh MangukiyaView Answer on Stackoverflow
Solution 6 - JsonmezoniView Answer on Stackoverflow