对于网络请求返回的 Json 数据,一般会进行如下解析:
- 将 Json String 解析为 Map<String, dynamic>
- 将 Json String 解析为 Dart Model
发起一个返回 Json String 的网络请求
import 'package:http/http.dart' as http;void main() {_doGet();
}_doGet() async {var url =Uri.parse("https://cx.shouji.360.cn/phonearea.php?number=17688888888");var response = await http.get(url);if (response.statusCode == 200) {//请求成功print("请求成功:");String jsonStr = response.body;print(jsonStr); // {"code":"0","data":{"province":"广东","city":"广州","sp":"联通"}}} else {//请求失败print("请求失败:");print("错误码:${response.statusCode}");print("错误信息:${response.body}");}
}
该请求返回的数据结构为
{"code":"0","data":{"province":"广东","city":"广州","sp":"联通"}
}
1、Json String 转 Map<String, dynamic>
引入
import 'dart:convert';
jsonDecode()
_json2Map(String jsonStr) {Map<String, dynamic> map1 = jsonDecode(jsonStr);print(map1['code']); // 0print(map1['data']); // {province: 广东, city: 广州, sp: 联通}Map<String, dynamic> map2 = map1['data'];print(map2['province']); // 广东print(map2['city']); // 广州print(map2['sp']); // 联通
}
2、Json String 转 Dart Model
Json String 转 Model 中 Model 的要求:
- 字段不能为私有
- 普通构造函数
- 声明为 XXX.fromJson 的命名构造函数
- 声明为 Map<String, dynamic> toJson() 成员函数
Model
{"code":"0","data":{"province":"广东","city":"广州","sp":"联通"}
}
class Location {String? province;String? city;String? sp;Location({this.province, this.city, this.sp});Location.fromJson(Map<String, dynamic> json) {province = json['province'];city = json['city'];sp = json['sp'];}Map<String, dynamic> toJson() {final Map<String, dynamic> data = <String, dynamic>{};data['province'] = province;data['city'] = city;data['sp'] = sp;return data;}
}
//4、声明为Map<String, dynamic> toJson成员函数
class DataModel {int? code;Location? data;DataModel({this.code, this.data});DataModel.fromJson(Map<String, dynamic> json) {code = json['code'];//注意此处传值data = Location.fromJson(json['data']);}Map<String, dynamic> toJson() {final Map<String, dynamic> d = <String, dynamic>{};d['code'] = code;//注意此处传值d['data'] = data?.toJson();return d;}
}
转换
_json2Model(String jsonStr) {Map<String, dynamic> map = jsonDecode(jsonStr);DataModel model = DataModel.fromJson(map);print(model.code); // 0print(model.data?.toJson()); // {province: 广东, city: 广州, sp: 联通}print(model.data?.province); // 广东print(model.data?.city); // 广州print(model.data?.sp); // 联通
}
在线转换工具
Json String 转 Dart Model 在线工具Í
3、界面实例
main.dart
import 'package:flutter/material.dart';
import 'Json2MapModelPage.dart';void main() {runApp(const MyApp());
}class MyApp extends StatelessWidget {const MyApp({super.key});Widget build(BuildContext context) {return MaterialApp(title: 'Leon Demo',theme: ThemeData(primarySwatch: Colors.blue,),home: const Json2MapModelPage(),);}
}
Json2MapModelPage.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'DataModel.dart';class Json2MapModelPage extends StatefulWidget {const Json2MapModelPage({super.key});State<Json2MapModelPage> createState() => _Json2MapModelPageState();
}class _Json2MapModelPageState extends State<Json2MapModelPage> {final String _jsonStr ='{"code":"0","data":{"province":"广东","city":"广州","sp":"联通"}}';var showResultJson2Map = "";var showResultJson2Model = "";Widget build(BuildContext context) {return Scaffold(appBar: AppBar(title: const Text("Json 解析 Demo"),),body: Column(children: [_json2MapBtn(),Text("json 2 map 解析结果:\n $showResultJson2Map"),_json2ModelBtn(),Text("json 2 Model 解析结果:\n $showResultJson2Model"),],),);}_json2MapBtn() {return ElevatedButton(onPressed: _json2map, child: const Text('Json 转 Map'));}void _json2map() {Map<String, dynamic> map = jsonDecode(_jsonStr);setState(() {showResultJson2Map ="code: ${map['code']}\ndata: ${map['data']}\nprovince: ${map['data']['province']} city: ${map['data']['city']} sp: ${map['data']['sp']}";});}_json2ModelBtn() {return ElevatedButton(onPressed: _json2Model, child: const Text('Json 转 Model'));}void _json2Model() {PhoneModel model = PhoneModel.fromJson(jsonDecode(_jsonStr));setState(() {showResultJson2Model ="code: ${model.code}\ndata: ${model.data?.toJson()}\nprovince: ${model.data?.province} city: ${model.data?.city} sp: ${model.data?.sp}";});}
}
DataModel.dart
利用在线转换工具转换
///
/// Code generated by jsonToDartModel https://ashamp.github.io/jsonToDartModel/
///
class PhoneModelData {
/*
{"province": "广东","city": "广州","sp": "联通"
}
*/String? province;String? city;String? sp;PhoneModelData({this.province,this.city,this.sp,});PhoneModelData.fromJson(Map<String, dynamic> json) {province = json['province']?.toString();city = json['city']?.toString();sp = json['sp']?.toString();}Map<String, dynamic> toJson() {final data = <String, dynamic>{};data['province'] = province;data['city'] = city;data['sp'] = sp;return data;}
}class PhoneModel {
/*
{"code": "0","data": {"province": "广东","city": "广州","sp": "联通"}
}
*/String? code;PhoneModelData? data;PhoneModel({this.code,this.data,});PhoneModel.fromJson(Map<String, dynamic> json) {code = json['code']?.toString();data =(json['data'] != null) ? PhoneModelData.fromJson(json['data']) : null;}Map<String, dynamic> toJson() {final data = <String, dynamic>{};data['code'] = code;if (data != null) {data['data'] = this.data!.toJson();}return data;}
}