62

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?

Christopher Moore
  • 15,626
  • 10
  • 42
  • 52
Notheros
  • 2,137
  • 9
  • 23
  • 34

6 Answers6

109

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

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
73

Just use

json.decode()

or

jsonDecode()

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

Ensure to import 'dart:convert';

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
16

You need to use import 'dart:convert';

Decode : JsonDecoder().convert("$response");

Encode : JsonEncoder().convert(object)

Sanjayrajsinh
  • 15,014
  • 7
  • 73
  • 78
6

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

RDR_Dev
  • 101
  • 1
  • 3
2

encoding json.encode() or jsonEncode()

decoding json.decode() or jsonDecode()

Example JSON Encoding

import 'dart:convert';
 void main() {
 final products = [
 {'id': 1, 'name': 'Product #1'},
 {'id': 2, 'name': 'Product #2'}
 ];
 print(json.encode(products));
}

Example: JSON decoding

import 'dart:convert';
import 'package:flutter/foundation.dart';

void main() {
 const String responseData =
   '[{"id":1,"name":"Product #1"},{"id":2,"name":"Product #2"}]';

  final products = json.decode(responseData);

  if (kDebugMode) {
   // Print the type of "products"
   print(products.runtimeType);

   // Print the name of the second product in the list
   print(products[1]['name']);
   }
    }
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
1

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);
mezoni
  • 10,684
  • 4
  • 32
  • 54