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

1,083 阅读4分钟

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

数据源:

{
    "count": "string",
    "total_page": "string",
    "list": [
        {
            "local_order_id": "string",
            "paid_price": "string",
            "pay_type": "string",
            "create_time": "string",
            "order_status": "string",
            "product_name": "string",
            "product_type": 0,
            "zs_id": "string",
            "product_id": "string",
            "price": "string"
        }
    ],
    "array": [
        1,
        2,
        3
    ],
    "object": {
        "string": "text",
        "number": 42,
        "bool": true,
        "array": [
            1,
            2,
            3
        ]
    }
}

工具一:JSON to Dart Converter

推荐系数: ⭐️⭐️

JSON to Dart Converter是一个免费的在线 Dart 模型类生成器。唯一可用的选项是将字段设为私有。在这种情况下,会生成 getter 和 setter。

class Autogenerated {
  String _count;
  String _totalPage;
  List<List> _list;
  List<int> _array;
  Object _object;

  Autogenerated(
      {String count,
      String totalPage,
      List<List> list,
      List<int> array,
      Object object}) {
    this._count = count;
    this._totalPage = totalPage;
    this._list = list;
    this._array = array;
    this._object = object;
  }

  String get count => _count;
  set count(String count) => _count = count;
  String get totalPage => _totalPage;
  set totalPage(String totalPage) => _totalPage = totalPage;
  List<List> get list => _list;
  set list(List<List> list) => _list = list;
  List<int> get array => _array;
  set array(List<int> array) => _array = array;
  Object get object => _object;
  set object(Object object) => _object = object;

  Autogenerated.fromJson(Map<String, dynamic> json) {
    _count = json['count'];
    _totalPage = json['total_page'];
    if (json['list'] != null) {
      _list = new List<List>();
      json['list'].forEach((v) {
        _list.add(new List.fromJson(v));
      });
    }
    _array = json['array'].cast<int>();
    _object =
        json['object'] != null ? new Object.fromJson(json['object']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['count'] = this._count;
    data['total_page'] = this._totalPage;
    if (this._list != null) {
      data['list'] = this._list.map((v) => v.toJson()).toList();
    }
    data['array'] = this._array;
    if (this._object != null) {
      data['object'] = this._object.toJson();
    }
    return data;
  }
}

class List {
  String _localOrderId;
  String _paidPrice;
  String _payType;
  String _createTime;
  String _orderStatus;
  String _productName;
  int _productType;
  String _zsId;
  String _productId;
  String _price;

  List(
      {String localOrderId,
      String paidPrice,
      String payType,
      String createTime,
      String orderStatus,
      String productName,
      int productType,
      String zsId,
      String productId,
      String price}) {
    this._localOrderId = localOrderId;
    this._paidPrice = paidPrice;
    this._payType = payType;
    this._createTime = createTime;
    this._orderStatus = orderStatus;
    this._productName = productName;
    this._productType = productType;
    this._zsId = zsId;
    this._productId = productId;
    this._price = price;
  }

  String get localOrderId => _localOrderId;
  set localOrderId(String localOrderId) => _localOrderId = localOrderId;
  String get paidPrice => _paidPrice;
  set paidPrice(String paidPrice) => _paidPrice = paidPrice;
  String get payType => _payType;
  set payType(String payType) => _payType = payType;
  String get createTime => _createTime;
  set createTime(String createTime) => _createTime = createTime;
  String get orderStatus => _orderStatus;
  set orderStatus(String orderStatus) => _orderStatus = orderStatus;
  String get productName => _productName;
  set productName(String productName) => _productName = productName;
  int get productType => _productType;
  set productType(int productType) => _productType = productType;
  String get zsId => _zsId;
  set zsId(String zsId) => _zsId = zsId;
  String get productId => _productId;
  set productId(String productId) => _productId = productId;
  String get price => _price;
  set price(String price) => _price = 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 Map<String, dynamic> data = new Map<String, dynamic>();
    data['local_order_id'] = this._localOrderId;
    data['paid_price'] = this._paidPrice;
    data['pay_type'] = this._payType;
    data['create_time'] = this._createTime;
    data['order_status'] = this._orderStatus;
    data['product_name'] = this._productName;
    data['product_type'] = this._productType;
    data['zs_id'] = this._zsId;
    data['product_id'] = this._productId;
    data['price'] = this._price;
    return data;
  }
}

class Object {
  String _string;
  int _number;
  bool _bool;
  List<int> _array;

  Object({String string, int number, bool bool, List<int> array}) {
    this._string = string;
    this._number = number;
    this._bool = bool;
    this._array = array;
  }

  String get string => _string;
  set string(String string) => _string = string;
  int get number => _number;
  set number(int number) => _number = number;
  bool get bool => _bool;
  set bool(bool bool) => _bool = bool;
  List<int> get array => _array;
  set array(List<int> array) => _array = array;

  Object.fromJson(Map<String, dynamic> json) {
    _string = json['string'];
    _number = json['number'];
    _bool = json['bool'];
    _array = json['array'].cast<int>();
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['string'] = this._string;
    data['number'] = this._number;
    data['bool'] = this._bool;
    data['array'] = this._array;
    return data;
  }
}

JSON 可以转换为 Dart 类,但存在主要问题:

  • 没有零安全性
  • 为私有字段生成 Getter 和 setter

工具二:JSON formatter

推荐系数: ⭐️

JSON formatter是另一个免费的在线 Dart 模型类生成器。没有可供选择的选项,您只需输入 JSON,该工具会将其转换为 Dart 类。

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

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

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

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

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

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

fromJson输出是无用的,甚至没有toJson包括方法。 没有空安全, 没有final字段, 但至少对象结构被正确转换。

工具三:JSON to Dart Model

推荐系数: ⭐️⭐️⭐️

JSON to Dart Model为输出提供了许多自定义选项。该代码是开源的,该项目似乎不像 quicktype 那样出名,但生成的代码将在当前 Dart 版本中开箱即用。

///
/// Code generated by jsonToDartModel https://ashamp.github.io/jsonToDartModel/
///
const String _jsonKeySomeRootEntityCount = 'count';
const String _jsonKeySomeRootEntityTotalPage = 'total_page';
const String _jsonKeySomeRootEntityList = 'list';
const String _jsonKeySomeRootEntityArray = 'array';
const String _jsonKeySomeRootEntityObject = 'object';
const String _jsonKeySomeRootEntityObjectString = 'string';
const String _jsonKeySomeRootEntityObjectNumber = 'number';
const String _jsonKeySomeRootEntityObjectTheBool = 'bool';
const String _jsonKeySomeRootEntityObjectArray = 'array';
class SomeRootEntityObject {
/*
{
  "string": "text",
  "number": 42,
  "bool": true,
  "array": [
    1
  ]
} 
*/

  String? string;
  int? number;
  bool? theBool;
  List<int?>? array;

  SomeRootEntityObject({
    this.string,
    this.number,
    this.theBool,
    this.array,
  });
  SomeRootEntityObject.fromJson(Map<String, dynamic> json) {
    string = json[_jsonKeySomeRootEntityObjectString]?.toString();
    number = json[_jsonKeySomeRootEntityObjectNumber]?.toInt();
    theBool = json[_jsonKeySomeRootEntityObjectTheBool];
  if (json[_jsonKeySomeRootEntityObjectArray] != null) {
  final v = json[_jsonKeySomeRootEntityObjectArray];
  final arr0 = <int>[];
  v.forEach((v) {
  arr0.add(v.toInt());
  });
    array = arr0;
    }
  }
  Map<String, dynamic> toJson() {
    final data = <String, dynamic>{};
    data[_jsonKeySomeRootEntityObjectString] = string;
    data[_jsonKeySomeRootEntityObjectNumber] = number;
    data[_jsonKeySomeRootEntityObjectTheBool] = theBool;
    if (array != null) {
      final v = array;
      final arr0 = [];
  v!.forEach((v) {
  arr0.add(v);
  });
      data[_jsonKeySomeRootEntityObjectArray] = arr0;
    }
    return data;
  }
}

const String _jsonKeySomeRootEntityListLocalOrderId = 'local_order_id';
const String _jsonKeySomeRootEntityListPaidPrice = 'paid_price';
const String _jsonKeySomeRootEntityListPayType = 'pay_type';
const String _jsonKeySomeRootEntityListCreateTime = 'create_time';
const String _jsonKeySomeRootEntityListOrderStatus = 'order_status';
const String _jsonKeySomeRootEntityListProductName = 'product_name';
const String _jsonKeySomeRootEntityListProductType = 'product_type';
const String _jsonKeySomeRootEntityListZsId = 'zs_id';
const String _jsonKeySomeRootEntityListProductId = 'product_id';
const String _jsonKeySomeRootEntityListPrice = 'price';
class SomeRootEntityList {
/*
{
  "local_order_id": "string",
  "paid_price": "string",
  "pay_type": "string",
  "create_time": "string",
  "order_status": "string",
  "product_name": "string",
  "product_type": 0,
  "zs_id": "string",
  "product_id": "string",
  "price": "string"
} 
*/

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

  SomeRootEntityList({
    this.localOrderId,
    this.paidPrice,
    this.payType,
    this.createTime,
    this.orderStatus,
    this.productName,
    this.productType,
    this.zsId,
    this.productId,
    this.price,
  });
  SomeRootEntityList.fromJson(Map<String, dynamic> json) {
    localOrderId = json[_jsonKeySomeRootEntityListLocalOrderId]?.toString();
    paidPrice = json[_jsonKeySomeRootEntityListPaidPrice]?.toString();
    payType = json[_jsonKeySomeRootEntityListPayType]?.toString();
    createTime = json[_jsonKeySomeRootEntityListCreateTime]?.toString();
    orderStatus = json[_jsonKeySomeRootEntityListOrderStatus]?.toString();
    productName = json[_jsonKeySomeRootEntityListProductName]?.toString();
    productType = json[_jsonKeySomeRootEntityListProductType]?.toInt();
    zsId = json[_jsonKeySomeRootEntityListZsId]?.toString();
    productId = json[_jsonKeySomeRootEntityListProductId]?.toString();
    price = json[_jsonKeySomeRootEntityListPrice]?.toString();
  }
  Map<String, dynamic> toJson() {
    final data = <String, dynamic>{};
    data[_jsonKeySomeRootEntityListLocalOrderId] = localOrderId;
    data[_jsonKeySomeRootEntityListPaidPrice] = paidPrice;
    data[_jsonKeySomeRootEntityListPayType] = payType;
    data[_jsonKeySomeRootEntityListCreateTime] = createTime;
    data[_jsonKeySomeRootEntityListOrderStatus] = orderStatus;
    data[_jsonKeySomeRootEntityListProductName] = productName;
    data[_jsonKeySomeRootEntityListProductType] = productType;
    data[_jsonKeySomeRootEntityListZsId] = zsId;
    data[_jsonKeySomeRootEntityListProductId] = productId;
    data[_jsonKeySomeRootEntityListPrice] = price;
    return data;
  }
}

class SomeRootEntity {
/*
{
  "count": "string",
  "total_page": "string",
  "list": [
    {
      "local_order_id": "string",
      "paid_price": "string",
      "pay_type": "string",
      "create_time": "string",
      "order_status": "string",
      "product_name": "string",
      "product_type": 0,
      "zs_id": "string",
      "product_id": "string",
      "price": "string"
    }
  ],
  "array": [
    1
  ],
  "object": {
    "string": "text",
    "number": 42,
    "bool": true,
    "array": [
      1
    ]
  }
} 
*/

  String? count;
  String? totalPage;
  List<SomeRootEntityList?>? list;
  List<int?>? array;
  SomeRootEntityObject? object;

  SomeRootEntity({
    this.count,
    this.totalPage,
    this.list,
    this.array,
    this.object,
  });
  SomeRootEntity.fromJson(Map<String, dynamic> json) {
    count = json[_jsonKeySomeRootEntityCount]?.toString();
    totalPage = json[_jsonKeySomeRootEntityTotalPage]?.toString();
  if (json[_jsonKeySomeRootEntityList] != null) {
  final v = json[_jsonKeySomeRootEntityList];
  final arr0 = <SomeRootEntityList>[];
  v.forEach((v) {
  arr0.add(SomeRootEntityList.fromJson(v));
  });
    list = arr0;
    }
  if (json[_jsonKeySomeRootEntityArray] != null) {
  final v = json[_jsonKeySomeRootEntityArray];
  final arr0 = <int>[];
  v.forEach((v) {
  arr0.add(v.toInt());
  });
    array = arr0;
    }
    object = (json[_jsonKeySomeRootEntityObject] != null) ? SomeRootEntityObject.fromJson(json[_jsonKeySomeRootEntityObject]) : null;
  }
  Map<String, dynamic> toJson() {
    final data = <String, dynamic>{};
    data[_jsonKeySomeRootEntityCount] = count;
    data[_jsonKeySomeRootEntityTotalPage] = totalPage;
    if (list != null) {
      final v = list;
      final arr0 = [];
  v!.forEach((v) {
  arr0.add(v!.toJson());
  });
      data[_jsonKeySomeRootEntityList] = arr0;
    }
    if (array != null) {
      final v = array;
      final arr0 = [];
  v!.forEach((v) {
  arr0.add(v);
  });
      data[_jsonKeySomeRootEntityArray] = arr0;
    }
    if (object != null) {
      data[_jsonKeySomeRootEntityObject] = object!.toJson();
    }
    return data;
  }
}

转换后的 JSON 片段作为注释包含在代码中。另外,数组的转换看起来很麻烦。可悲的是,转换器创建了两个名称不同的相同对象。但除此之外,它看起来还不错。但是,我不会使用结果,因为代码风格很奇怪,我必须做很多重构。