fluttercandies / JsonToDart

The tool to convert json to dart code, support Windows,Mac,Web.
MIT License
355 stars 42 forks source link

添加生成copy方法 #13

Closed zafkielkurumi closed 2 years ago

zmtzawqlp commented 3 years ago

better jsonDecode(jsonEncode(this))

zafkielkurumi commented 3 years ago

import 'dart:convert'; T? asT(dynamic value) { if (value is T) { return value; } return null; }

class Root { Root({ this.a, });

factory Root.fromJson(Map<String, dynamic> jsonRes) => Root( a: jsonRes['a'] == null ? null : A.fromJson(asT<Map<String, dynamic>>(jsonRes['a'])!), );

A? a;

@override String toString() { return jsonEncode(this); }

Map<String, dynamic> toJson() => <String, dynamic>{ 'a': a, };

Root copy() { return Root( a: a?.copy(), ); }

Root clone() => Root.fromJson(asT<Map<String, dynamic>>(jsonDecode(jsonEncode(this)))!); }

class A { A({ this.b, this.e, });

factory A.fromJson(Map<String, dynamic> jsonRes) { final List? b = jsonRes['b'] is List ? [] : null; if (b != null) { for (final dynamic item in jsonRes['b']!) { if (item != null) { b.add(asT(item)!); } } }

final List<E>? e = jsonRes['e'] is List ? <E>[] : null;
if (e != null) {
  for (final dynamic item in jsonRes['e']!) {
    if (item != null) {
      e.add(E.fromJson(asT<Map<String, dynamic>>(item)!));
    }
  }
}
return A(
  b: b,
  e: e,
);

}

List? b; List? e;

@override String toString() { return jsonEncode(this); }

Map<String, dynamic> toJson() => <String, dynamic>{ 'b': b, 'e': e, };

A copy() { return A( b: b?.map((int e) => e).toList(), e: e?.map((E e) => e.copy()).toList(), ); }

A clone() => A.fromJson(asT<Map<String, dynamic>>(jsonDecode(jsonEncode(this)))!); }

class E { E({ this.g, });

factory E.fromJson(Map<String, dynamic> jsonRes) => E( g: asT<int?>(jsonRes['g']), );

int? g;

@override String toString() { return jsonEncode(this); }

Map<String, dynamic> toJson() => <String, dynamic>{ 'g': g, };

E copy() { return E( g: g, ); }

E clone() => E.fromJson(asT<Map<String, dynamic>>(jsonDecode(jsonEncode(this)))!); }

zmtzawqlp commented 3 years ago

thanks for your contribution. we should make sure following cases with Test Json https://github.com/fluttercandies/JsonToDart/blob/master/test.txt

  1. non-nullsafety
  2. nullsafety, nullable
  3. nullsafety, non-nullable

and there are some thing error with hive need to be updated. please update code see whether meet your request

zafkielkurumi commented 3 years ago

完全符合,没有任何问题