没有注释的代码不是好代码
没有demo的文章不是好文章
本文demo请点击 github
什么是JSON
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一个子集。
术语:
编码 将数据结构(一般是自定义对象)转换为字符串。
解码 将字符串转换为数据结构(一般是自定义对象)。
现在手机应用与后端的交互大部分通过http协议通讯,手机端调用http接口请求后端,后端返回相应的数据给手机端,一般http协议会通过http响应头和http响应体在手机端和后端之间传递数据。
http接口响应体一般都是返回json格式的字符串,手机应用获取到这些json字符串一般都要处理成相应的自定义对象来使用
json字符串在Android中转成自定义对象
在Android里json字符串最直接的数据结构对应对象是JSONObject,JSONObject可以把一个Json字符串转成一个JSONObject对象,然后根据key方便的取出里面的value。当然一般写代码时都是把json字符串转成自定义对象使用,而不是直接使用JSONObject
假设有一个自定义对象(以kotlin为例)
1 2 3 4 5 6 7 8 9 | package com.example.androidapplication class TechnologyCompany(val name:String,val products:List<Product>); class Product(val name:String) { override fun toString(): String { return "name:$name"; } } |
现在通过http接口或者读取到持久化存储得到一个字符串
1 2 3 4 5 6 | val jsonStr = """ { "name":"google", "products":[{"name":"android os"},{"name":"flutter"}] } """; |
如何把内存中的字符串对象转成一个自定义对象呢
在Android里使用org.json库把json字符串转成JSONObject再转成自定义对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | //kotlin使用org.json.JSONObject val jsonStr = """ { "name":"google", "products":[{"name":"android os"},{"name":"flutter"}] } """; var googleObject = JSONObject(jsonStr); Log.d("log",googleObject.toString()); var name = googleObject.optString("name"); var products = googleObject.optJSONArray("products"); var productList = mutableListOf<Product>(); var len = if(products==null||products.length()<=0) 0 else products.length(); for (i in 0..len) { if(i <= len-1) productList.add(Product(products.getJSONObject(i).optString("name"))); } var google = TechnologyCompany(name,productList); Log.d("log",google.name); Log.d("log",google.products.toString()); |
在Android里使用Gson库直接把json字符串转成自定义对象
1 2 3 4 | //这是kotlin代码,和java代码差不多,原理都一样的。 var google = Gson().fromJson(jsonStr,TechnologyCompany::class.java); Log.d("log",google.name); Log.d("log",google.products.toString()); |
小结
从上面的代码可知,Gson的主要工作是,把手动取json键值,然后把对应键值赋给自定义对象相应的成员属性的工作封装在内部,开发人员只需要关心类成员属性的定义就好了,省略代码,减少出错,
dart:convert与在Android里使用Gson库直接把json字符串转成自定义对象类似,都需要手动解释json键值然后赋值给类对象的成员属性
使用 dart:convert 手动序列化 JSON 数据
新建Dart自定义对象类
1 2 3 4 5 6 7 8 9 10 11 12 | class TechnologyCompany{ String name; List<Product> products; TechnologyCompany(this.name, this.products); } class Product{ String name; Product(this.name); } |
使用dart:convert库把json字符串转成 Map
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import 'dart:convert'; import 'TechnologyCompany.dart'; void main() { var jsonStr = ''' { "name":"google", "products":[{"name":"android os"},{"name":"flutter"}] } '''; var map = jsonDecode(jsonStr); var list = <Product>[]; var products = map["products"]; if(products is List) { products.forEach((p){ list.add(Product(p["name"])); }); } var google = TechnologyCompany(map["name"],list); print("name:${google.name}"); print("name:${google.products}"); } |
例用dart:convert库把json转成自定义对象的过程,和Android使用org.json库把json字符串转成对象过程类似,都要转成先转成一个中间类型JSONObject或者Map 然后再根据key取出value,再把取出来的值用于自定义对象构造函数,或都通过get set填充到自定义对象。这一个过程是很麻烦的。那么在Dart里有没有像Gson那样的库,可以一句代码,直接把json字符串转成自定义对象呢?答案是没有的
Flutter 中是否有 GSON/Jackson/Moshi 的等价物
简单来说是没有。
这样的库需要使用运行时 反射,这在 Flutter 中是被禁用的。运行时反射会影响被 Dart 支持了相当久的 tree shaking。通过 tree shaking,你可以从你的发布版本中“抖掉”不需要使用的代码。这会显著优化 App 的体积。
由于反射会默认让所有的代码被隐式使用,这让 tree shaking变得困难。工具不知道哪一部分在运行时不会被用到,所以冗余的代码很难被清除。当使用反射时,App 的体积不能被轻易优化。
在dart中使用类似Gson的方案
因为Flutter不支持反射,所以在Flutter里要把一个json字符串转成自定义对象,一定要先把json字符串转成Map
在dart中虽然没有Gson那样的库可以直接把一个json对象转成自定义对象,但是dart有类似于gson的类库,可以使开发人员只需要定义类成员属性,不需要关心手动解释json的过程,那就是json_serializable
json_serializable在Flutter里的使用
1.添加依赖
在pubspec.yaml文件里添加相应依赖
1 2 3 4 5 6 | dependencies: json_annotation: ^3.0.0 dev_dependencies: build_runner: ^1.0.0 json_serializable: ^3.2.0 |
编写Dart类,并使用相应注解
1.导入 import 'package:json_annotation/json_annotation.dart';
2.手动添加part这一行(当前文件名.g.dart)例如
3.使用@JsonSerializable() @JsonKey()注解
4.编写xxxFromJson和xxToJson方法
5.运行命令生成补全代码
可以安装AndroidStudio的
下面以官方示例为例,请自行体会
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | part "example_json_annotation.g.dart"; import 'package:json_annotation/json_annotation.dart'; //手动添加这一行(当前文件名.g.dart) part "example_json_annotation.g.dart"; //使用注解 @JsonSerializable() class Person { //不需要特殊处理的成员属性不需要加注解,会自动把json字符串里相应的键值取出赋值给这一个成员属性 final String firstName; @JsonKey(includeIfNull: false) final String middleName; final String lastName; @JsonKey(name: 'date-of-birth', nullable: false) final DateTime dateOfBirth; @JsonKey(name: 'last-order') final DateTime lastOrder; @JsonKey(nullable: false) List<Order> orders; Person(this.firstName, this.lastName, this.dateOfBirth, {this.middleName, this.lastOrder, List<Order> orders}) : orders = orders ?? <Order>[]; factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json); Map<String, dynamic> toJson() => _$PersonToJson(this); } @JsonSerializable(includeIfNull: false) class Order { int count; int itemNumber; bool isRushed; Item item; @JsonKey( name: 'prep-time', fromJson: _durationFromMilliseconds, toJson: _durationToMilliseconds) Duration prepTime; @JsonKey(fromJson: _dateTimeFromEpochUs, toJson: _dateTimeToEpochUs) final DateTime date; Order(this.date); factory Order.fromJson(Map<String, dynamic> json) => _$OrderFromJson(json); Map<String, dynamic> toJson() => _$OrderToJson(this); static Duration _durationFromMilliseconds(int milliseconds) => milliseconds == null ? null : Duration(milliseconds: milliseconds); static int _durationToMilliseconds(Duration duration) => duration?.inMilliseconds; static DateTime _dateTimeFromEpochUs(int us) => us == null ? null : DateTime.fromMicrosecondsSinceEpoch(us); static int _dateTimeToEpochUs(DateTime dateTime) => dateTime?.microsecondsSinceEpoch; } @JsonSerializable() class Item { int count; int itemNumber; bool isRushed; Item(); factory Item.fromJson(Map<String, dynamic> json) => _$ItemFromJson(json); Map<String, dynamic> toJson() => _$ItemToJson(this); } @JsonLiteral('config.json') Map get glossaryData => _$glossaryDataJsonLiteral; |
json_serializable库使用总结
共三个注解
JsonSerializable
JsonKey
JsonLiteral
注JsonSerializable()注解的类一定要有构造函数,否则转换失败
普通用法1
只在
高级用法1
复杂对象转换
1 2 3 | @JsonKey(name: 'prep-time',fromJson: 方法名称,toJson: 方法名称) @JsonKey(fromJson: 方法名称, toJson: 方法名称) |
fromJson json字符串转成对象时用 基本数据类型转成复杂对象
toJson 对象转成字符串时使用 复杂对象转成基本数据类型
高级用法2.
1 2 | @JsonLiteral('config.json') 根据json文件生成对应map集合,适合做配置文件时使用 |
编码
编码即把自定义对象转成json字符串,json_serializable库已经可以把编码