Flutter 中的 JSON 解析,Android架构师成长路线

本文详细介绍了在Flutter中处理JSON解析的常见情况,包括包含数组的对象、对象嵌套以及复杂的对象数组嵌套。通过实例展示了如何避免类型错误,成功将JSON数据转化为 Dart 对象。最后,文章总结了作者对于Android开发现状的见解,并鼓励开发者共同学习进步。
摘要由CSDN通过智能技术生成

return person;
}

输入如下:

flutter: jsonMap runType is _InternalLinkedHashMap<String, dynamic>
flutter: person name is jack, age is 18, height is 175.0

可以看出 json.decode(personJson) 方法返回的类型为 _InternalLinkedHashMap<String, dynamic> ,意思就是这个 Map 的 key 为 String 类型,而 value 的类型为 dynamic 的,也就是动态的,就如 person.json 中,key 都是 String 类型的,但是 value 可能是 String 、int、double 等等类型。

包含数组的对象

定义一个 country.json 如下:

{
“name”: “China”,
“cities”: [
“Beijing”,
“Shanghai”
]
}

实体类如下:

class Country {
String name;
List cities;

Country({this.name, this.cities});

factory Country.fromJson(Map<String, dynamic> json) {
return Country(name: json[‘name’], cities: json[‘cities’]);
}
}

Service 类如下:

import ‘dart:async’;
import ‘package:flutter/services.dart’;
import ‘dart:convert’;
import ‘…/models/country.dart’;

Future _loadCountryJson() async {
return await rootBundle.loadString(‘assets/country.json’);
}

Future decodeCountry() async {
String countryJson = await _loadCountryJson();

Map<String, dynamic> jsonMap = json.decode(countryJson);

Country country = Country.fromJson(jsonMap);
print(‘country name is ${country.name}’);
return country;
}

然后我们在 main() 中去调用 decodeCountry() 运行,<

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值