Flutter 序列化JSON数据

Dart Json序列化

dart:convert 库提供了对json的支持

jsonDecode可以将json字符串转换为Map,jsonEncode可以将对象序列化为json字符串

import 'dart:convert';
void main(){
  String jsonString = '{"name":"John Smith","email":"john@example.com"}';
  Map<String, dynamic> userMap = jsonDecode(jsonString);
  print(userMap);// {name: John Smith, email: john@example.com}
  print(jsonEncode(userMap));// {"name":"John Smith","email":"john@example.com"}
}

同时,提供了对类的序列化支持

创建一个模型类

为模型类添加fromJson的构造方法,以及toJson方法

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

void main(){
    String jsonString = '{"name":"John Smith","email":"john@example.com"}';
    Map<String, dynamic> userMap = jsonDecode(jsonString);
    User user = User.fromJson(userMap);//使用fromJson方法解码,获取一个User的实例
    print(jsonEncode(user));//使用jsonEncode方法将User的实例编码成字符串
}

Flutter JSON序列化

使用json_serializable处理序列化

引入依赖:

dependencies:
  json_annotation: 4.3.0
  
dev_dependencies:
  build_runner: 2.1.5
  json_serializable: 6.0.1

创建实体类,指定@JsonSerializable() 注解

import 'package:json_annotation/json_annotation.dart';
​
part 'user.g.dart';//固定写法
​
@JsonSerializable()
class User {
    String name;
    String email;
    
    @JsonKey(name: "first_name")
    final String firstname;// 使用JsonKey指定json的属性值
    
    User(this.name, this.email,this.firstname);
    
    factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);//固定写法
    
    Map<String, dynamic> toJson() => _$UserToJson(this);//固定写法
}

运行命令生成代码:

flutter pub run build_runner build

本文来自博客园,作者:Bin_x,转载请注明原文链接:https://www.cnblogs.com/Bin-x/p/15539567.html

原文地址:https://www.cnblogs.com/Bin-x/p/15539567.html