Add JSON serializer to every model class?

JsonDart

Json Problem Overview


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.

Let's say we have a bunch of model classes (PODOs) such as:

class Customer
{
  int Id;
  String Name;
}

Now, I'd love to be able to just JSON-encode my domain objects like this:

var customer = new Customer()
  ..Id = 17
  ..Name = "John";
var json = JSON.encode(customer);

Unfortunately, this won't work...

Uncaught Error: Converting object to an encodable object failed.
Stack Trace: 
#0      _JsonStringifier.stringifyValue (dart:convert/json.dart:416)
#1      _JsonStringifier.stringify (dart:convert/json.dart:336)
#2      JsonEncoder.convert (dart:convert/json.dart:177)
....

... unless we explicitly tell dart:convert how to encode:

class Customer
{
  int Id;
  String Name;
  
  Map toJson() { 
    Map map = new Map();
    map["Id"] = Id;
    map["Name"] = Name;
    return map;
  }  
}

Do I really have to add a toJson method to every single one of my model classes, or is there a better way?

EDIT: this is the simple serialization I'm looking for:

{
    "Id": 17,
    "Name": "John"
}

Compare to ToJson in ServiceStack.Text, for instance.

Dart's serialization library (see Matt B's answer below) seems like a step in the right direction. However, this ...

var serialization = new Serialization()
  ..addRuleFor(Customer); 
var json = JSON.encode(serialization.write(customer, format: new SimpleJsonFormat()));

... produces just an array with the values (no keys):

[17,"John"]

Using the default SimpleMapFormat on the other hand generates this complex representation.

Still haven't found what I'm looking for...

EDIT 2: Adding some context: I'm building a RESTful web service in Dart, and I'm looking for a JSON serialization which can easily be consumed by any client, not just another Dart client. For instance, querying the Stack Exchange API for this very question will create this JSON response. This is the serialization format I'm looking for. - Or, look at typical JSON responses returned by the Twitter REST API or the Facebook Graph API.

EDIT 3: I wrote a small blog post about this. See also the discussion on Hacker News.

Json Solutions


Solution 1 - Json

IMO this is a major short-coming in Dart, surprising given its Web Application focus. I would've thought that having JSON support in the standard libraries would've meant that serializing classes to and from JSON would work like water, unfortunately the JSON support seems incomplete, where it appears the choices are to work with loosely typed maps or suffer through un-necessary boilerplate to configure your standard (PODO) classes to serialize as expected.

Without Reflection and Mirrors support

As popular Dart platforms like Flutter doesn't support Reflection/Mirrors your only option is to use a code-gen solution. The approach we've taken in ServiceStack's native support for Dart and Flutter lets you generate typed Dart models for all your ServiceStack Services from a remote URL, e.g:

$ npm install -g @servicestack/cli

$ dart-ref https://techstacks.io

> Supported in .NET Core and any of .NET's popular hosting options.

The example above generates a Typed API for the .NET TechStacks project using the generated DTOs from techstacks.io/types/dart endpoint. This generates models following Dart's JsonCodec pattern where you can customize serialization for your Dart models by providing a fromJson named constructor and a toJson() instance method, here's an example of one of the generated DTOs:

class UserInfo implements IConvertible
{
    String userName;
    String avatarUrl;
    int stacksCount;

    UserInfo({this.userName,this.avatarUrl,this.stacksCount});
    UserInfo.fromJson(Map<String, dynamic> json) { fromMap(json); }

    fromMap(Map<String, dynamic> json) {
        userName = json['userName'];
        avatarUrl = json['avatarUrl'];
        stacksCount = json['stacksCount'];
        return this;
    }

    Map<String, dynamic> toJson() => {
        'userName': userName,
        'avatarUrl': avatarUrl,
        'stacksCount': stacksCount
    };

    TypeContext context = _ctx;
}

With this model you can use Dart's built-in json:convert APIs to serialize and deserialize your model to JSON, e.g:

//Serialization
var dto = new UserInfo(userName:"foo",avatarUrl:profileUrl,stacksCount:10);
String jsonString = json.encode(dto);

//Deserialization
Map<String,dynamic> jsonObj = json.decode(jsonString);
var fromJson = new UserInfo.fromJson(jsonObj);

The benefit of this approach is that it works in all Dart platforms, including Flutter and AngularDart or Dart Web Apps with and without Dart 2’s Strong Mode.

The generated DTOs can also be used with servicestack's Dart package to enable an end to end typed solution which takes care JSON serialization into and out of your typed DTOs, e.g:

var client = new JsonServiceClient("https://www.techstacks.io");
var response = await client.get(new GetUserInfo(userName:"mythz"));

For more info see docs for ServiceStack's native Dart support.

Dart with Mirrors

If you're using Dart in a platform where Mirrors support is available I've found using a Mixin requires the least effort, e.g:

import 'dart:convert';
import 'dart:mirrors';

abstract class Serializable {

  Map toJson() { 
    Map map = new Map();
    InstanceMirror im = reflect(this);
    ClassMirror cm = im.type;
    var decls = cm.declarations.values.where((dm) => dm is VariableMirror);
    decls.forEach((dm) {
      var key = MirrorSystem.getName(dm.simpleName);
      var val = im.getField(dm.simpleName).reflectee;
      map[key] = val;
    });
    
    return map;
  }  

}

Which you can mixin with your PODO classes with:

class Customer extends Object with Serializable
{
  int Id;
  String Name;
}

Which you can now use with JSON.encode:

var c = new Customer()..Id = 1..Name = "Foo";
  
print(JSON.encode(c));

Result:

{"Id":1,"Name":"Foo"}
Note: see caveats with using Mirrors

Solution 2 - Json

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.

Solution 3 - Json

An alternative is to use the Serialization package and add rules for your classes. The most basic form uses reflection to get the properties automatically.

Solution 4 - Json

Redstone mapper is the best serialization library I've used. JsonObject and Exportable have the downside that you have to extend some of their classes. With Redstone Mapper you can have structures like this

class News
{
    @Field() String title;
    @Field() String text;
    @Field() List<FileDb> images;
    @Field() String link; 
}

It works with getters and setters, you can hide information by not annotating it with @Field(), you can rename field from/to json, have nested objects, it works on the server and client. It also integrates with the Redstone Server framework, where it has helpers to encode/decode to MongoDB.

The only other framework I've seen thats on the right direction is Dartson, but it still lack some features compared to Redstone Mapper.

Solution 5 - Json

I have solved with:

class Customer extends JsonObject
{
  int Id;
  String Name;
  Address Addr;
}

class Address extends JsonObject{
  String city;
  String State;
  String Street;
}

But my goal is bind data from/to json from/to model classes; This solution work if you can modify model classes, in a contrast you must use solution "external" to convert model classes;

see also: https://stackoverflow.com/questions/14462007

Solution 6 - Json

Another package solving this problem is built_value:

https://github.com/google/built_value.dart

With built_value your model classes look like this:

abstract class Account implements Built<Account, AccountBuilder> {
  static Serializer<Account> get serializer => _$accountSerializer;

  int get id;
  String get name;
  BuiltMap<String, JsonObject> get keyValues;

  factory Account([updates(AccountBuilder b)]) = _$Account;
  Account._();
}

Note that built_value isn't just about serialization -- it also provides operator==, hashCode, toString, and a builder class.

Solution 7 - Json

I have achieve with this:

To make this work, pass explicitToJson: true in the @JsonSerializable() annotation over the class declaration. The User class now looks as follows:

import 'address.dart';
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';

@JsonSerializable(explicitToJson: true)
class User {
  String firstName;
  Address address;

  User(this.firstName, this.address);

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
  Map<String, dynamic> toJson() => _$UserToJson(this);
}

You can check here: https://flutter.dev/docs/development/data-and-backend/json#generating-code-for-nested-classes

Solution 8 - Json

I prefer using https://ashamp.github.io/jsonToDartModel/ online tool write by myself.

It has features below:

  • online use, without plugin
  • support multidimensional list
  • support complex json
  • support convert all props to String type
  • empty props warning
  • single file
  • dart keyword protected
  • instant convert

I think it's better than other tools.Welcome if you have any suggestion, issue or bug report.

Solution 9 - Json

Some of the answers are no longer applicable to Flutter 2; here is the process for automatically creating toJson and fromJson methods:

https://flutter.dev/docs/development/data-and-backend/json#creating-model-classes-the-json_serializable-way

PS: I wish this would be as simple as using Newtonsoft library in Asp.Net, this solution is closest to an automated solution

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMaxView Question on Stackoverflow
Solution 1 - JsonmythzView Answer on Stackoverflow
Solution 2 - JsonLeksatView Answer on Stackoverflow
Solution 3 - JsonMatt BView Answer on Stackoverflow
Solution 4 - JsonCristian GarciaView Answer on Stackoverflow
Solution 5 - JsonDomenico MonacoView Answer on Stackoverflow
Solution 6 - JsonDavid MorganView Answer on Stackoverflow
Solution 7 - JsonRaj KateshiyaView Answer on Stackoverflow
Solution 8 - Jsonuser3044484View Answer on Stackoverflow
Solution 9 - JsondvdmnView Answer on Stackoverflow