【发布时间】:2019-05-15 02:48:38
【问题描述】:
我在this article 中发现了一个有用的解析复杂 JSON 工具。 The tool 将采用 JSON 示例并以您选择的编程语言对其进行解析。
我目前正在使用 Dart 以及我的简单原始 JSON“内容”示例:
{
"title": "Welcome to quicktype!"
}
被这个 JSON tool in Dart 解析创建这个 Dart 类:
import 'dart:convert';
Content contentFromJson(String str) => Content.fromJson(json.decode(str));
String contentToJson(Content data) => json.encode(data.toJson());
class Content {
String title;
Content({
this.title,
});
factory Content.fromJson(Map<String, dynamic> json) => new Content(
title: json["title"],
);
Map<String, dynamic> toJson() => {
"title": title,
};
}
在这种情况下,工厂构造函数的目的是什么?没有存储 Content 类实例的“私有”变量。没有检查缓存或键,以便在使用相同原始 JSON 数据参数的后续 Content.fromJson 调用中返回已实例化的 Content 类。
因为使用了 factory 关键字,这是否意味着 Dart 仅仅因为该方法被表示为工厂构造函数,就在后台处理重用相同的实例化?
【问题讨论】: