How to decode JSON in Flutter?

后端 未结 5 2029
独厮守ぢ
独厮守ぢ 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: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 : {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 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 args) {
      testParseJsonObject();
    }
    
    // Output
    Student: {name = John, age = 20}
    

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

提交回复
热议问题