Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

Flutter - The best way to parse a JSON

I'm trying to parse JSON to an object in Dart, the documentation uses Map type to parse a JSON response.I have about 200 list on data form json file.

My result data to list of all record and render it to ListView in flutter. I have push code in github. https://github.com/phuochoit/user_list

[
  id,
  name,
  username,
  email,
  phone 
] 

JSON

 {
      "type": "user",
      "format": "json",
      "version": "1.0",
      "data": {
        "[email protected]": {
          "id": 1,
          "name": "Leanne Graham",
          "username": "Bret",
          "email": "[email protected]",
          "address": {
            "street": "Kulas Light",
            "suite": "Apt. 556",
            "city": "Gwenborough",
            "zipcode": "92998-3874",
            "geo": {
              "lat": "-37.3159",
              "lng": "81.1496"
            }
          },
          "phone": "1-770-736-8031 x56442",
          "website": "hildegard.org",
          "company": {
            "name": "Romaguera-Crona",
            "catchPhrase": "Multi-layered client-server neural-net",
            "bs": "harness real-time e-markets"
          }
        },
        "[email protected]": {
          "id": 2,
          "name": "Ervin Howell",
          "username": "Antonette",
          "email": "[email protected]",
          "address": {
            "street": "Victor Plains",
            "suite": "Suite 879",
            "city": "Wisokyburgh",
            "zipcode": "90566-7771",
            "geo": {
              "lat": "-43.9509",
              "lng": "-34.4618"
            }
          },
          "phone": "010-692-6593 x09125",
          "website": "anastasia.net",
          "company": {
            "name": "Deckow-Crist",
            "catchPhrase": "Proactive didactic contingency",
            "bs": "synergize scalable supply-chains"
          }
        },
.... to be continued
      }
    }

I have code get json file and decode it in dart but i not map data to render

Future<UserModel> fetchUser() async {
      final response = await http.get('http://172.16.0.2/data/users.json');
    
      if (response.statusCode == 200) {
        // If the server did return a 200 OK response,
        // then parse the JSON.
    
        return UserModel.fromJson(jsonDecode(response.body));
      } else {
        // If the server did not return a 200 OK response,
        // then throw an exception.
        throw Exception('Failed to load album');
      }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Compare this with things like quicktype: (1) If you do not have a model class, then try to use things like quicktype to get that class from a sample json string. (2) However, I suggest not to use the toJson and fromJson given by quicktype. The reason is that, when your model changes (say add a field / change a field), you must also change your toJson/fromJson accordingly (which is time-consuming and error-prone). Otherwise you get a bug.

If you already have your model class and only need the toJson and fromJson methods: Then the very famous json_serializable package suits you. It will happily generate the toJson and fromJson.

For example, say you have

class Person {
  final String firstName;
  final String lastName;
  final DateTime dateOfBirth;
}

Then with a bit of boilerplate code, it will auto give you

Person _$PersonFromJson(Map<String, dynamic> json) {
  return Person(
    firstName: json['firstName'] as String,
    lastName: json['lastName'] as String,
    dateOfBirth: DateTime.parse(json['dateOfBirth'] as String),
  );
}

Map<String, dynamic> _$PersonToJson(Person instance) => <String, dynamic>{
      'firstName': instance.firstName,
      'lastName': instance.lastName,
      'dateOfBirth': instance.dateOfBirth.toIso8601String(),
    };

Actually that package is more powerful than that. Check out the link for more details.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...