Flutter/Dart 开发者的 6 个 JsonToDart 工具对比 ----- 第二篇

449 阅读4分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第7天,点击查看活动详情

工具四:Quicktype

推荐系数: ⭐️⭐️⭐️⭐️

Quicktype是 JSON 对象的多语言转换器,它还支持 Dart。有一些选项可以自定义生成的类,还有一个 Visual Studio Code 的扩展。

// To parse this JSON data, do
//
//     final welcome = welcomeFromMap(jsonString);

import 'package:meta/meta.dart';
import 'dart:convert';

Welcome welcomeFromMap(String str) => Welcome.fromMap(json.decode(str));

String welcomeToMap(Welcome data) => json.encode(data.toMap());

class Welcome {
    Welcome({
        @required this.count,
        @required this.totalPage,
        @required this.list,
        @required this.array,
        @required this.object,
    });

    final String count;
    final String totalPage;
    final List<ListElement> list;
    final List<int> array;
    final Object object;

    factory Welcome.fromMap(Map<String, dynamic> json) => Welcome(
        count: json["count"] == null ? null : json["count"],
        totalPage: json["total_page"] == null ? null : json["total_page"],
        list: json["list"] == null ? null : List<ListElement>.from(json["list"].map((x) => ListElement.fromMap(x))),
        array: json["array"] == null ? null : List<int>.from(json["array"].map((x) => x)),
        object: json["object"] == null ? null : Object.fromMap(json["object"]),
    );

    Map<String, dynamic> toMap() => {
        "count": count == null ? null : count,
        "total_page": totalPage == null ? null : totalPage,
        "list": list == null ? null : List<dynamic>.from(list.map((x) => x.toMap())),
        "array": array == null ? null : List<dynamic>.from(array.map((x) => x)),
        "object": object == null ? null : object.toMap(),
    };
}

class ListElement {
    ListElement({
        @required this.localOrderId,
        @required this.paidPrice,
        @required this.payType,
        @required this.createTime,
        @required this.orderStatus,
        @required this.productName,
        @required this.productType,
        @required this.zsId,
        @required this.productId,
        @required this.price,
    });

    final String localOrderId;
    final String paidPrice;
    final String payType;
    final String createTime;
    final String orderStatus;
    final String productName;
    final int productType;
    final String zsId;
    final String productId;
    final String price;

    factory ListElement.fromMap(Map<String, dynamic> json) => ListElement(
        localOrderId: json["local_order_id"] == null ? null : json["local_order_id"],
        paidPrice: json["paid_price"] == null ? null : json["paid_price"],
        payType: json["pay_type"] == null ? null : json["pay_type"],
        createTime: json["create_time"] == null ? null : json["create_time"],
        orderStatus: json["order_status"] == null ? null : json["order_status"],
        productName: json["product_name"] == null ? null : json["product_name"],
        productType: json["product_type"] == null ? null : json["product_type"],
        zsId: json["zs_id"] == null ? null : json["zs_id"],
        productId: json["product_id"] == null ? null : json["product_id"],
        price: json["price"] == null ? null : json["price"],
    );

    Map<String, dynamic> toMap() => {
        "local_order_id": localOrderId == null ? null : localOrderId,
        "paid_price": paidPrice == null ? null : paidPrice,
        "pay_type": payType == null ? null : payType,
        "create_time": createTime == null ? null : createTime,
        "order_status": orderStatus == null ? null : orderStatus,
        "product_name": productName == null ? null : productName,
        "product_type": productType == null ? null : productType,
        "zs_id": zsId == null ? null : zsId,
        "product_id": productId == null ? null : productId,
        "price": price == null ? null : price,
    };
}

class Object {
    Object({
        @required this.string,
        @required this.number,
        @required this.objectBool,
        @required this.array,
    });

    final String string;
    final int number;
    final bool objectBool;
    final List<int> array;

    factory Object.fromMap(Map<String, dynamic> json) => Object(
        string: json["string"] == null ? null : json["string"],
        number: json["number"] == null ? null : json["number"],
        objectBool: json["bool"] == null ? null : json["bool"],
        array: json["array"] == null ? null : List<int>.from(json["array"].map((x) => x)),
    );

    Map<String, dynamic> toMap() => {
        "string": string == null ? null : string,
        "number": number == null ? null : number,
        "bool": objectBool == null ? null : objectBool,
        "array": array == null ? null : List<dynamic>.from(array.map((x) => x)),
    };
}

结果包含所有内容,但存在问题:

  • Quicktype 不使用required关键字,而是使用旧的@required注解
  • Quicktype 不支持空值安全,而是使用 == null ? null : value

这使得代码在没有手动更改的情况下无法使用。而且作者有一段时间没有进行更新了。

工具五:Dart QuickType

推荐系数: ⭐️⭐️⭐️⭐️⭐️

Dart QuickType是 Quicktype 的一个分支,具有更新的代码库。所有提到的 Quicktype 缺陷都在这里得到修复,创建的 Dart 代码看起来简单而苗条。

class Icc {
    Icc({
        required this.count,
        required this.totalPage,
        required this.list,
        required this.array,
        required this.object,
    });

    final String? count;
    final String? totalPage;
    final List<ListElement> list;
    final List<int> array;
    final Object? object;

    factory Icc.fromJson(Map<String, dynamic> json){ 
        return Icc(
        count: json["count"],
        totalPage: json["total_page"],
        list: json["list"] == null ? [] : List<ListElement>.from(json["list"]!.map((x) => ListElement.fromJson(x))),
        array: json["array"] == null ? [] : List<int>.from(json["array"]!.map((x) => x)),
        object: json["object"] == null ? null : Object.fromJson(json["object"]),
    );
    }

}

class ListElement {
    ListElement({
        required this.localOrderId,
        required this.paidPrice,
        required this.payType,
        required this.createTime,
        required this.orderStatus,
        required this.productName,
        required this.productType,
        required this.zsId,
        required this.productId,
        required this.price,
    });

    final String? localOrderId;
    final String? paidPrice;
    final String? payType;
    final String? createTime;
    final String? orderStatus;
    final String? productName;
    final int? productType;
    final String? zsId;
    final String? productId;
    final String? price;

    factory ListElement.fromJson(Map<String, dynamic> json){ 
        return ListElement(
        localOrderId: json["local_order_id"],
        paidPrice: json["paid_price"],
        payType: json["pay_type"],
        createTime: json["create_time"],
        orderStatus: json["order_status"],
        productName: json["product_name"],
        productType: json["product_type"],
        zsId: json["zs_id"],
        productId: json["product_id"],
        price: json["price"],
    );
    }

}

class Object {
    Object({
        required this.string,
        required this.number,
        required this.objectBool,
        required this.array,
    });

    final String? string;
    final int? number;
    final bool? objectBool;
    final List<int> array;

    factory Object.fromJson(Map<String, dynamic> json){ 
        return Object(
        string: json["string"],
        number: json["number"],
        objectBool: json["bool"],
        array: json["array"] == null ? [] : List<int>.from(json["array"]!.map((x) => x)),
    );
    }

}

工具六:JSON to Dart online converter Null Safety

推荐系数: ⭐️⭐️

JSON to Dart online converter Null Safety除了设置类名之外没有其他选项,并且生成的代码不能开箱即用。

class AutoGenerate {
  AutoGenerate({
    required this.count,
    required this.totalPage,
    required this.list,
    required this.array,
    required this.object,
  });
  late final String count;
  late final String totalPage;
  late final List<List> list;
  late final List<int> array;
  late final Object object;
  
  AutoGenerate.fromJson(Map<String, dynamic> json){
    count = json['count'];
    totalPage = json['total_page'];
    list = List.from(json['list']).map((e)=>List.fromJson(e)).toList();
    array = List.castFrom<dynamic, int>(json['array']);
    object = Object.fromJson(json['object']);
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['count'] = count;
    _data['total_page'] = totalPage;
    _data['list'] = list.map((e)=>e.toJson()).toList();
    _data['array'] = array;
    _data['object'] = object.toJson();
    return _data;
  }
}

class List {
  List({
    required this.localOrderId,
    required this.paidPrice,
    required this.payType,
    required this.createTime,
    required this.orderStatus,
    required this.productName,
    required this.productType,
    required this.zsId,
    required this.productId,
    required this.price,
  });
  late final String localOrderId;
  late final String paidPrice;
  late final String payType;
  late final String createTime;
  late final String orderStatus;
  late final String productName;
  late final int productType;
  late final String zsId;
  late final String productId;
  late final String price;
  
  List.fromJson(Map<String, dynamic> json){
    localOrderId = json['local_order_id'];
    paidPrice = json['paid_price'];
    payType = json['pay_type'];
    createTime = json['create_time'];
    orderStatus = json['order_status'];
    productName = json['product_name'];
    productType = json['product_type'];
    zsId = json['zs_id'];
    productId = json['product_id'];
    price = json['price'];
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['local_order_id'] = localOrderId;
    _data['paid_price'] = paidPrice;
    _data['pay_type'] = payType;
    _data['create_time'] = createTime;
    _data['order_status'] = orderStatus;
    _data['product_name'] = productName;
    _data['product_type'] = productType;
    _data['zs_id'] = zsId;
    _data['product_id'] = productId;
    _data['price'] = price;
    return _data;
  }
}

class Object {
  Object({
    required this.string,
    required this.number,
    required this.bool,
    required this.array,
  });
  late final String string;
  late final int number;
  late final bool bool;
  late final List<int> array;
  
  Object.fromJson(Map<String, dynamic> json){
    string = json['string'];
    number = json['number'];
    bool = json['bool'];
    array = List.castFrom<dynamic, int>(json['array']);
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['string'] = string;
    _data['number'] = number;
    _data['bool'] = bool;
    _data['array'] = array;
    return _data;
  }
}

这段代码的一些缺陷:

  • 使用时不需要late的关键字required
  • 变量可以像关键字一样命名→编译器错误
  • 创建两个相同的类ObjectList
  • fromJson方法中没有fallback
  • 创建的类的其他编译器错误

以上就是想介绍的6个JsonToDart 工具