简体   繁体   English

从 Flutter 文件中的 json 文件自动生成 class 和成员

[英]Auto-generate class and member from json file in Flutter

I have a simple json file like below.我有一个简单的 json 文件,如下所示。 This is fixed in the project.这在项目中是固定的。

{
    "en": "English",
    "es": "Español",
    "fr": "Français"
}

My question is, is it possible to do a auto-generate work to create a class with members which return the value of each key?我的问题是,是否可以进行自动生成工作来创建一个 class 的成员,这些成员返回每个键的值? The result of the auto-generate can be similar to below example.自动生成的结果可能类似于下面的示例。 So every time I add new key and value to the json file, this class will generate or update that new item into it.因此,每次我向 json 文件添加新键和值时,此 class 都会生成或更新该新项目。

class JsonHelper {
    static String get en => json['en'];

    static String get es => json['es'];

    static String get fr => json['fr'];
}

you can use this site for Auto-generate class in Flutter:您可以使用此站点在 Flutter 中自动生成 class:

https://app.quicktype.io/?share=pxoAci2ZiiPtLyjXaYhD https://app.quicktype.io/?share=pxoAci2ZiiPtLyjXaYhD

another way is using Auto-generator package of npm另一种方法是使用 npm 的自动生成器 package

Yes for sure you can use Auto-generate class in Flutter on this website: Instantly parse Json是的,您可以在本网站上的 Flutter 中使用 Auto-generate class : Instantly parse Json

Example例子

 // To parse this JSON data, do // // final autoGenerate = autoGenerateFromJson(jsonString); import 'dart:convert'; AutoGenerate autoGenerateFromJson(String str) => AutoGenerate.fromJson(json.decode(str)); String autoGenerateToJson(AutoGenerate data) => json.encode(data.toJson()); class AutoGenerate { AutoGenerate({ this.en, this.es, this.fr, }); String en; String es; String fr; factory AutoGenerate.fromJson(Map<String, dynamic> json) => AutoGenerate( en: json["en"], es: json["es"], fr: json["fr"], ); Map<String, dynamic> toJson() => { "en": en, "es": es, "fr": fr, }; }

you can then simply use final objectFromClass = autoGenerateFromJson(jsonString)然后你可以简单地使用final objectFromClass = autoGenerateFromJson(jsonString)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM