当前位置:网站首页>How does flutter use the online transcoding tool to convert JSON to model

How does flutter use the online transcoding tool to convert JSON to model

2022-06-24 22:04:00 One leaf floating boat

Domestic tycoon CrazyCodeBoy Tools provided :

JSON turn Dart - CrazyCodeBoy Technology blog official website of |CrazyCodeBoy|Devio| Focus on mobile technology development (Android&IOS)、Flutter Development 、Flutter course 、React Native Development 、React Native course 、React Native Blog

Text begins .

The goal is json:

{
    "posts": [
      {
        "id": "0",
        "created": 1590453935992,
        "content": " Offer based on GraphQL API Data query and access ,「Hasura」 a 990 Thousands of dollars A round ..."
      },
      {
        "id": "1",
        "created": 1590453935992,
        "content": " Why? GraphQL yes API The future of "
      },
      {
        "id": "2",
        "created": 1590453935992,
        "content": "Netflix: Why do we have to  GraphQL  Introduce front-end architecture ?"
      }
    ]
}

open quicktype Website ( Scientific access to the web may be required ):Instantly parse JSON in any language | quicktype

Click on the top right corner Options Button , And make the following configuration :

Paste JSON Go to the input box , And enter the model name in the upper left corner PostsData

The right side will automatically generate the model :

Copy the code on the right , Create related types :

/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,
    };
}

complete ,Good Job!


Other online conversion tools

One . Generate websites online :

https://javiercbk.github.io/json_to_dart/

Two . JsonToDart plug-in unit 【 recommend 】

stay Android Studio Install in JsonToDart plug-in unit ,

a. open Preferences(Mac) perhaps Setting(Window),

b. choice Plugins, Search for JsonToDart

Click on Install( The picture above has been installed ), After the installation is completed, restart

Select directory , Click on the right , choice New->Json to Dart

take json Copy the string in , Fill in the class description , Click on Generate button

With shortcut keys : 

Windows:ALT + Shift + D

Mac:Option + Shift + D
 

3、 ... and .  high efficiency JSON turn Model

  1. stay pubspec.yaml Add dependency to
json_annotation: ^3.1.0
json_serializable: ^3.5.0
build_runner: ^1.0.0

stay Android Stuido In the implementation of Pub get

  1. New model class (mode/demo_model.dart)
class DemoModel{
    
}
  1. Send the back end request to the web page JSON Data to Model:

    https://czero1995.github.io/json-to-model/: Website transformation supports the transformation of complex objects with infinite levels

  • For example, the following JSON Copy the data to the web page ( On the left ):
{
  "code": 0,
  "data": {
    "avatar": "xxx.png",
    "id": 7,
    "float":0.1,
    "is_deleted": false,
    "nickname": "nickName",
    "openId": null,
    "phone": "13641418383",
    "store_ids": [1,2],
    "updated": "2020-11-05 11:53:10",
    "more":[{"a":1,"b":"b","c":{"c1":0.2,"c2":2}}]
  }
}
  • And then convert to Model data ( On the right )
import 'package:json_annotation/json_annotation.dart';
part 'demo_model_data.g.dart'; 
@JsonSerializable(explicitToJson: true)
class DemoModelModel {
    DemoModelData data;
    DemoModelModel({
      this.data,
      this.code,
      this.message
    });
    factory DemoModelModel.fromJson(Map<String, dynamic> json) => _$DemoModelModelFromJson(json);
    Map<String, dynamic> toJson() => _$DemoModelModelToJson(this);
}

@JsonSerializable(explicitToJson: true)
class DemoModelData {
    String avatar;
    int id;
    double float;
    bool is_deleted;
    String nickname;
    var openId;
    String phone;
    List<int> store_ids; 
    String updated;
    List<MoreData> more; 
    DemoModelData({
        this.avatar, 
        this.id, 
        this.float, 
        this.is_deleted, 
        this.nickname, 
        this.openId, 
        this.phone, 
        this.store_ids, 
        this.updated, 
        this.more, 
    });
  factory DemoModelData.fromJson(Map<String, dynamic> json) => _$DemoModelDataFromJson(json);
  Map<String, dynamic> toJson() => _$DemoModelDataToJson(this);
}

@JsonSerializable(explicitToJson: true) 
class MoreData{ 
    int a;
    String b;
    CData c;
    MoreData({
        this.a, 
        this.b, 
        this.c, 
    });
    factory MoreData.fromJson(Map<String, dynamic> json) => _$MoreDataFromJson(json);
    Map<String, dynamic> toJson() => _$MoreDataToJson(this);
}

@JsonSerializable(explicitToJson: true) 
class CData{ 
    double c1;
    int c2;
    CData({
        this.c1, 
        this.c2, 
    });
    factory CData.fromJson(Map<String, dynamic> json) => _$CDataFromJson(json);
    Map<String, dynamic> toJson() => _$CDataToJson(this);
}

After that, the data will be copied out and then covered demo_model.dart On the file

  1. perform build_runner

Execute the command in the project terminal :

flutter pub run build_runner build

After execution , Will generate demo_model.g.dart file

The whole execution process is as follows ( Open the link below to view )

https://image-static.segmentfault.com/305/532/3055326920-21e28cc64f409c11

Four . JSON to Dart Converter 

JSON to Dart Converter - Convert JSON Code Online

原网站

版权声明
本文为[One leaf floating boat]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206241535282886.html