Flutter 如何使用在线转码工具将 JSON 转为 Model

3,160 阅读1分钟

目标 json:

{
    "posts": [
      {
        "id": "0",
        "created": 1590453935992,
        "content": "提供基于GraphQL API的数据查询及访问,「Hasura」获990万美元A轮..."
      },
      {
        "id": "1",
        "created": 1590453935992,
        "content": "为什么GraphQL是API的未来"
      },
      {
        "id": "2",
        "created": 1590453935992,
        "content": "Netflix:我们为什么要将 GraphQL 引入前端架构?"
      }
    ]
}

打开 quicktype 网站(可能需要科学访问网络):app.quicktype.io/

点击右上角 Options 按钮,并作如下配置:

粘贴 JSON 到输入框中,并在左上角输入模型名称 PostsData

右侧会自动生成模型:

复制右侧代码,创建相关类型:

/lib/PostsData.dart:

// To parse this JSON data, do
//
//     final postsData = postsDataFromJson(jsonString);

import 'dart:convert';

class PostsData {
    final List<Post> posts;

    PostsData({
        this.posts,
    });

    factory PostsData.fromJson(String str) => PostsData.fromMap(json.decode(str));

    String toJson() => json.encode(toMap());

    factory PostsData.fromMap(Map<String, dynamic> json) => PostsData(
        posts: json["posts"] == null ? null : List<Post>.from(json["posts"].map((x) => Post.fromMap(x))),
    );

    Map<String, dynamic> toMap() => {
        "posts": posts == null ? null : List<dynamic>.from(posts.map((x) => x.toMap())),
    };
}

class Post {
    final String id;
    final int created;
    final String content;

    Post({
        this.id,
        this.created,
        this.content,
    });

    factory Post.fromJson(String str) => Post.fromMap(json.decode(str));

    String toJson() => json.encode(toMap());

    factory Post.fromMap(Map<String, dynamic> json) => Post(
        id: json["id"] == null ? null : json["id"],
        created: json["created"] == null ? null : json["created"],
        content: json["content"] == null ? null : json["content"],
    );

    Map<String, dynamic> toMap() => {
        "id": id == null ? null : id,
        "created": created == null ? null : created,
        "content": content == null ? null : content,
    };
}

完成,Good Job!