Flutter中JSON序列化与反序列化

最近在自学flutter项目,想不到起步就碰到了一个小麻烦,由于没有接触过dart语法,所以很自然以一个前端的心态去调试写demo 。 在vuereact开发中,我已经习惯了在控制台中打印出对象和数组直接查看数据结构,但是在flutter中需要对数组和对象进行序列化。

什么是序列化?一些复杂的原理之类的可以移步官方文档

flutterchina.club/json/

如果你想尝试更快的开始调试,请接着往下看。
首先我们可以定义一个数组,数组中是对象

class Post{
  String title;
  String author;
  String imageUrl;
  String id;

  Post({
    this.title,
    this.author,
    this.imageUrl,
    this.id
  });
} 

final List<Post> posts = [
  Post(
    id:'1',
    title:'clearlove',
    author: 'edg',
    imageUrl:'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=390994561,3187349009&fm=26&gp=0.jpg'
  ),
  Post(
    id:'2',
    title:'uzi',
    author: 'rng',
    imageUrl:'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2139334008,3056679607&fm=26&gp=0.jpg'
  ),
];
复制代码

如果我们不序列化,在vscode编辑器的调试控制台中是这样的

F5799780-A227-4BF8-90F4-D0838D2E8150.png
我们无法去看其中的数据结构 , 所以便于前端的开发工作,需要区序列化

class Post{
  var title;
  var author;
  var imageUrl;
  var id;

  Post({
    this.title,
    this.author,
    this.imageUrl,
    this.id
  });

  Post.fromJSON(Map<String, dynamic> json){
    title = json['title']?.toString();
    author = json['author']?.toString();
    imageUrl = json['imageUrl']?.toString();
    id = json['id']?.toString();
  }

  Map<String,dynamic>toJson(){
    final Map<String,dynamic> data = <String,dynamic>{};
    data['title'] = title;
    data['author'] = author;
    data['imageUrl'] = imageUrl;
    data['id'] = id;
    return data;
  }  
}

final List<Post> posts = [
  Post(
    id:'1',
    title:'clearlove',
    author: 'edg',
    imageUrl:'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=390994561,3187349009&fm=26&gp=0.jpg'
  ),
  Post(
    id:'2',
    title:'uzi',
    author: 'rng',
    imageUrl:'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2139334008,3056679607&fm=26&gp=0.jpg'
  ),
];


复制代码

我们序列化之后再去print(posts()),结果似乎没有什么变化,因为我们还差最后一步

打印数组和对象的时候我们需要print(jsonEncode(posts)),用jsonEncode方法

再来看看效果

obj.png

但是在日常开发中,数据肯定不会如此的简单,自然我们不会手动的去序列化,那么我们可以依赖工具。
首先添加依赖

  json_annotation: ^3.0.0
  build_runner: ^1.4.0
  json_serializable: ^3.2.3
复制代码

然后对原来的文件进行导入包,进行序列化

import 'package:json_annotation/json_annotation.dart';
import 'dart:core';
part 'post.g.dart';
@JsonSerializable()
class Post{
  var title;
  var author;
  var imageUrl;
  var id;

  Post({
    this.title,
    this.author,
    this.imageUrl,
    this.id
  });
  //反序列化
  factory Post.fromJson(Map<String, dynamic> json) => _$PostFromJson(json);
  //序列化
  Map<String, dynamic> toJson() => _$PostToJson(this);

}

final List<Post> posts = [
  Post(
    id:'1',
    title:'clearlove',
    author: 'edg',
    imageUrl:'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=390994561,3187349009&fm=26&gp=0.jpg'
  ),
  Post(
    id:'2',
    title:'uzi',
    author: 'rng',
    imageUrl:'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2139334008,3056679607&fm=26&gp=0.jpg'
  ),
];
复制代码

这个时候代码是报错的,可以看出多了一个新的文件 part ‘post.g.dart’;
你需要在文件目录下终端中运行flutter packages pub run build_runner build

生成的文件中是什么东西呢

// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'post.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

Post _$PostFromJson(Map<String, dynamic> json) {
  return Post(
    title: json['title'],
    author: json['author'],
    imageUrl: json['imageUrl'],
    id: json['id'],
  );
}

Map<String, dynamic> _$PostToJson(Post instance) => <String, dynamic>{
      'title': instance.title,
      'author': instance.author,
      'imageUrl': instance.imageUrl,
      'id': instance.id,
    };

复制代码

实际上和我们上面手动写的序列化是一样的,现在就可以愉快去调试了

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享