为每个模型类添加JSON序列化? [英] Add JSON serializer to every model class?

查看:255
本文介绍了为每个模型类添加JSON序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当涉及Dart中的JSON编码时,根据 Seth Ladd的accouncement ,最后批准现在正式的方式是 dart:convert + JSON.Encode

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.

假设我们有一堆模型类( PODO )例如:

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

class Customer
{
  int Id;
  String Name;
}

现在,我希望能够对我的域进行JSON编码对象如下:

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)
....


$ b b

...除非我们明确告诉 dart:convert 如何编码:

class Customer
{
  int Id;
  String Name;

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

我真的要添加<$ c $

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

EDIT

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

例如,在 ServiceStack.Text 中添加ToJson 。

Compare to ToJson in ServiceStack.Text, for instance.

Dart的序列化库(请参阅下面的Matt B的回答)似乎是朝正确方向迈出的一步。但是,此...

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"]


$ b b

使用默认 SimpleMapFormat a>另一方面生成此复杂的表示。

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

仍然没有找到我要找的...

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

编辑2 :添加一些上下文:在Dart中的RESTful Web服务,我正在寻找一个JSON序列化,可以很容易地被任何客户端使用,而不只是另一个Dart客户端。例如,查询Stack Exchange API查找这个问题将创建此JSON响应。这是我正在寻找的序列化格式。 - 或者,查看 Twitter REST API Facebook Graph API

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.

编辑3 :我写了一个小博客。另请参阅Hacker News上的讨论

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

推荐答案

IMO这是Dart的一个主要缺点,令人惊讶的是它的Web应用程序的重点。我认为在标准库中支持JSON将意味着将类和JSON串行化将像水一样工作,不幸的是,JSON支持似乎不完整,似乎选择是使用松散类型的映射还是遭受通过不必要的样板文件配置您的标准(PODO)类以按预期进行序列化。

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.

说过我发现使用Mixin需要最少的努力, / p>

Having said 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;
  }  

}

您可以与PODO类与:

Which you can mixin with your PODO classes with:

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

现在可以使用 JSON.encode

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

print(JSON.encode(c));

结果:

{"Id":1,"Name":"Foo"}

这篇关于为每个模型类添加JSON序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆