Flutter--网络请求(二)Json转换dart对象

JSON转换成Dart对象

  • 假设请求的返回的JSON数据如下
{“id" : 12345, "title" : "titleName"}
  • 对应的dart对象
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工具生成实体类

  • 在pubspec.yaml中引入下面的库
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);
}
  • 生成fromJson和toJson方法
在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,
    };
发布了175 篇原创文章 · 获赞 56 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_39424143/article/details/105008426