Add JSON serializer to every model class?

前端 未结 9 1462
南旧
南旧 2020-11-28 07:56

When it comes to JSON encoding in Dart, per Seth Ladd\'s accouncement the finally approved now official way to go is dart:convert + JSON.Encode.

9条回答
  •  误落风尘
    2020-11-28 08:30

    I wrote the Exportable library to solve such things like converting to Map or JSON. Using it, the model declaration looks like:

    import 'package:exportable/exportable.dart';
    
    class Customer extends Object with Exportable {
      @export int id;
      @export String name;
    }
    

    And if you want to convert to JSON, you may:

    String jsonString = customer.toJson();
    

    Also, it's easy to initialize new object from a JSON string:

    Customer customer = new Customer()..initFromJson(jsonString);
    

    Or alternatively:

    Customer customer = new Exportable(Customer, jsonString);
    

    Please, see the README for more information.

提交回复
热议问题