#####特点 flutter中 ,json.decode(jsonStr)后,所有的对象和数组包括其子孙对象和数组,都是以dynamic形式体现的,导致无法获取对象和数组的类型,也就无法在编译期使用类型的属性方法。难点就在于怎么把dynamic转为具体的类型。 #####目标,假如服务器返回的是这个格式的字符串,该怎么解析。
[{
"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"
}]
}
]
#####方式一,使用最直接的方式 首先文件中:import 'dart:convert'; 再定义几个类,在类的内部将dynamic转为具体的类型:
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));
});
}
}
测试:
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);
});
});
}