##### Features flutter, after json.decode(jsonStr), all objects and arrays, including their descendants, are represented as dynamic, which makes it impossible to obtain the types of objects and arrays, and thus to use the property methods of the types at compile time. The difficulty is how to convert dynamic into a concrete type. ##### target, if the server returns a string in this format, how to parse.
[{
"name": "jack",
"age": 18,
"sex": {
"boy": true,
"girl": false
},
"address": [{
"email": "xxx",
"code": "10000"
}]
},
{
"name": "tom",
"age": 28,
"sex": {
"boy": false,
"girl": true
},
"address": [{
"email": "yyyxxx",
"code": "1001100"
}]
}
]
Copy the code
##### Use the most direct method: import ‘dart:convert’; Define a few more classes that convert dynamic to a concrete type inside the class:
class Address { String email; String code; Address.from(dynamic d) {email = d["email"]; code = d["code"]; } } class Sex{ bool boy; bool girl; Sex. From (dynamic d){boy = d["boy"]; girl = d["girl"]; } } class Person { String name; int age; Sex sex; List<Address> address; Person.fromjson (dynamic json) {name = json["name"]; age = json["age"]; sex = new Sex.from(json["sex"]); List list = json["address"]; address = []; list.forEach((dynamic item) { address.add(new Address.from(item)); }); }}Copy the code
Testing:
void test03() { String jsonStr = '[{"name":"jack","age":18,"sex":{"boy":true,"girl":false},"address":[{"email":"xxx","code":"10000"}]},{"name":"tom","age ":28,"sex":{"boy":false,"girl":true},"address":[{"email":"yyyxxx","code":"1001100"}]}]'; List items = json.decode(jsonStr); List<Person> result = []; items.forEach((dynamic d) { result.add(new Person.fromJson(d)); }); Result. forEach((item) {print(item.name); print(item.age); print(item.sex.boy); print(item.sex.girl); item.address.forEach((ad) { print(ad.email); print(ad.code); }); }); }Copy the code