How to decode JSON in Flutter?

后端 未结 5 1998
独厮守ぢ
独厮守ぢ 2020-12-05 09:52

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, t

相关标签:
5条回答
  • 2020-12-05 10:06

    Just use

    json.decode()
    

    or

    jsonDecode()
    

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

    Ensure to import 'dart:convert';

    0 讨论(0)
  • 2020-12-05 10:17

    You need to use import 'dart:convert';

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

    Encode : JsonEncoder().convert(object)

    0 讨论(0)
  • 2020-12-05 10:18

    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

    0 讨论(0)
  • 2020-12-05 10:22

    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/

    0 讨论(0)
  • 2020-12-05 10:26

    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

    • Work with JSON in Flutter - Part 1: dart:convert
    • Work with JSON in Flutter - Part 2: json_serializable
    • Some Options for Deserializing JSON with Flutter
    0 讨论(0)
提交回复
热议问题