Flutter:写一个带 fromJson/toJson 的 Post 模型(JSON 解析)

有些知识点看十遍不如跑一遍。下面的代码就是为「写一个带 fromJson/toJson 的 Post 模型」准备的,跑完你会看到:从 Map 创建 Post,再转回 Map 打印。

示例代码

先把示例原样运行,确认输出;不要一上来就改结构,否则很难判断问题出在哪。

// 这段代码要解决的问题:从 Map 创建 Post,再转回 Map 打印
// 关键类/函数:
// - Post:文章数据模型
// - fromJson():从 Map 反序列化
// - toJson():序列化成 Map
// - build():根据当前状态生成界面

// 文章数据模型
class Post {
  const Post({required this.id, required this.title});

  final int id;
  final String title;

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(id: json['id'] as int, title: json['title'] as String);
  }

  Map<String, dynamic> toJson() => {'id': id, 'title': title};
}

void main() {
  final post = Post.fromJson({'id': 1, 'title': 'Hello'});
  print(post.toJson());
}

代码拆解

不必按顺序背 API,先盯住每个关键类/函数负责的那一段数据流。

  • Post:文章数据模型
  • fromJson():从 Map 反序列化
  • toJson():序列化成 Map

边界情况

一次改太多行,出错后不知道是哪一步引入的;改一行,跑一次。

接下来动手

  1. 把示例删到只剩最核心的几行,确认它还能跑;再逐行加回被删掉的部分。
  2. 把 Post 换成更小的版本,只保留当前示例需要的能力。

先把这一小段改到能解释每一行,再考虑加功能;慢一点反而更快。