简体   繁体   中英

Flutter how to parse JSON Mongodb data

I'm trying to parse some JSON data with mongodb. I have no data found I think that the problem is with the difference in field in mongodb data

{"imei":"865566048694354","_id":"5e7c996fd6eb5f039c50bd26","createdAt":"2020-03-26T12:00:47.021Z","updatedAt":"2020-03-26T12:00:47.021Z","__v":0},{"imei":{"test":{"tactileState":"ignore","pixelState":"ignore"},"name":"h12hhhhgkhh"},"_id":"5ea8357d8c562b3dd8fe5bf1","createdAt":"2020-04-28T13:54:05.094Z","updatedAt":"2020-04-28T13:54:05.094Z","__v":0},{"imei":{"test":{"tactileState":"ignore","pixelState":"ignore"},"name":"h12hhhhgkhh"},"_id":"5ea8366741a5e527446744a2","createdAt":"2020-04-28T13:57:59.035Z","updatedAt":"2020-04-28T13:57:59.035Z","__v":0},{"imei":{"test":{"tactileState":"ignore","pixelState":"ignore","greyState":"ignore"},"name":"h12hhhhgkhh"},"_id":"5ea837614cf7ed30f0163c38","createdAt":"2020-04-28T14:02:09.395Z","updatedAt":"2020-04-28T14:02:09.395Z","__v":0},{"imei":{"test":{"bafleState":"1","microState":"1","vibreurState":"1"},"name":"h12hhhhgkhh"},"_id":"5ea837854cf7ed30f0163c39","createdAt":"2020-04-28T14:02:45.287Z","updatedAt":"2020-04-28T14:02:45.287Z","__v":0}
   

If you can help me how to write the class and how to write the method in flutter because everything which I made always snapshot has no data I think that the problem in the difference in fields in mongodb data makes the problem because all tutorial and article which I see didn't use different database field always the same structure even with embedded document.

Suppose you have a json like this

{
 "name": "John Smith",
 "email": "john@example.com"
}

With `dart:convert, you can serialize this JSON model in two ways.

Map<String, dynamic> user = jsonDecode(jsonString);
print('Howdy, ${user['name']}!');

Or create a model like this

class User {
final String name;
final String email;

User(this.name, this.email);

User.fromJson(Map<String, dynamic> json)
  : name = json['name'],
    email = json['email'];

Map<String, dynamic> toJson() =>
{
  'name': name,
  'email': email,
};
}

And then use it like this:

Map userMap = jsonDecode(jsonString);
var user = User.fromJson(userMap);

print('Howdy, ${user.name}!');

Reference is here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM