Flutter Json序列化

一、使用dart:convert 手动序列化

user.dart

import 'dart:conbert'

class User {
	final String name;
	final String password;
	
	User(this.name, this.password);
	
	User.fromJson(Map<String, dynamic> json) {
		name = json['name'];
		password = json['password'];
	}
}

var userMap = json.decode(userJson);
User user = User.fromJson(userMap);

二、使用代码库json_annotation序列化

pubspec.yaml添加第三方库

dependencies:
  json_annotation: ^2.4.0
  
dev_dependencies:
  build_runner: ^1.2.8
  json_serializable: ^3.0.0

CommitComment.dart

import 'package:json_annotation/json_annotation.dart';

part 'CommitComment.g.dart';

//这个标注是告诉生成器,这个类是需要生成Model类的
@JsonSerializable()

class CommitComment{
  int id;
  String body;
  //这个标注是将后台返回的key转成我们自己想要的key
  @JsonKey(name: "created_at")
  DateTime createdAt;
  @JsonKey(name: "html_url")
  String htmlUrl;
  User user;
  int totalCommits;
  List<RepoCommit> commits;
  CommitComment(
      this.id,
      this.body,
      this.createdAt,
      this.htmlUrl,
      this.user,
      this.totalCommits,
      this.commits
      );
  factory CommitComment.fromJson(Map<String, dynamic> json) => _$CommitCommentFromJson(json);
  Map<String, dynamic> toJson() => _$CommitCommentToJson(this);
}

这么写完后下面3处都会报错,但没事,

//格式为 part '该类的类名.g.dart'; 这个类后面通过命令行自动生成
part 'Branch.g.dart';  

//JSON转模型的方法
factory Branch.fromJson(Map<String, dynamic> json) => _$BranchFromJson(json);

//模型转JSON的方法
Map<String, dynamic> toJson() => _$BranchToJson(this);

编译器里终端运行下面命令,之后等待创建CommitComment.g.dart文件就行

flutter packages pub run build_runner build

终端输出成功信息

[INFO] Succeeded after 838ms with 2 outputs (2 actions)

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值