JSON转换成Dart对象
{“id" : 12345, "title" : "titleName"}
class Article {
final String title;
// dynamic表示不知道传进去什么类型
Artilce.fromJson(Map<String, dynamic> json) {
id = json['id'];
title = json['title'];
}
}
- 注意:
- 在请求响应回来时,通过json.decode(responseData)可以将JSON结果转换成一个Map类型(对应JSON对象)或者List类型(对应JSON数组)
使用Json工具生成实体类
dependencies:
json_annotation: 3.0.1
dev_dependencies:
build_runner: 1.8.0
json_serializable: 3.2.5
import 'package:json_annotation/json_annotation.dart';
// 此时此处会报错,别急下面会作出处理
part 'home_article.g.dart';
// 首先使用注解声明
@JsonSerializable()
class HomeArticle extends Object {
// 使用JsonKey注解目的:有时实体类中的属性和服务器返回的Json字段是不同的,可以通过该注解指向正确的接口字段
@JsonKey(name: 'curPage')
int curPage;
@JsonKey(name: 'datas')
List<Article> datas;
@JsonKey(name: 'offset')
int offset;
@JsonKey(name: 'over')
bool over;
@JsonKey(name: 'pageCount')
int pageCount;
@JsonKey(name: 'size')
int size;
@JsonKey(name: 'total')
int total;
HomeArticle(
this.curPage,
this.datas,
this.offset,
this.over,
this.pageCount,
this.size,
this.total,
);
factory HomeArticle.fromJson(Map<String, dynamic> srcJson) =>
_$HomeArticleFromJson(srcJson);
Map<String, dynamic> toJson() => _$HomeArticleToJson(this);
}
在terminal中输入命令:
flutter packages pub run build_runner build
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'home_article.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
HomeArticle _$HomeArticleFromJson(Map<String, dynamic> json) {
return HomeArticle(
json['curPage'] as int,
(json['datas'] as List)
?.map((e) =>
e == null ? null : Article.fromJson(e as Map<String, dynamic>))
?.toList(),
json['offset'] as int,
json['over'] as bool,
json['pageCount'] as int,
json['size'] as int,
json['total'] as int,
);
}
Map<String, dynamic> _$HomeArticleToJson(HomeArticle instance) =>
<String, dynamic>{
'curPage': instance.curPage,
'datas': instance.datas,
'offset': instance.offset,
'over': instance.over,
'pageCount': instance.pageCount,
'size': instance.size,
'total': instance.total,
};