#####特點 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);
});
});
}
複製程式碼