Dart JSON解码器 [英] Dart JSON Decoder

查看:194
本文介绍了Dart JSON解码器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很惊讶dart没有内置的object-to-json和json-to-object映射器。

I am surprised that dart does not have a built in object-to-json and json-to-object mapper.

我读到我们必须自己编写映射,这是不愉快的。

I read that we have to hand code the mapping ourselves, which is not pleasant.

我没有彻底测试它的用例,我发现 dart-exportable 是非常有用的我的一半要求。

Anyways, although I have not thoroughly tested it for my use case, I found dart-exportable to be very helpful for half of my requirement.

任何建议的json对象解码软件包?

Any suggested package for json to object decoding?

推荐答案

最佳选择是使用 Smoke 图书馆。

Your best option is to use the Smoke library.

它是Mirrors功能的一个子集,但具有基于镜像和基于Codegen的实现。它由PolymerDart团队编写,因此它接近官方,我们将获得。

It's a subset of the Mirrors functionality but has both a Mirrors-based and a Codegen-based implementation. It's written by the PolymerDart team, so it's as close to "Official" as we're going to get.

在开发时,它将使用基于镜像的编码/解码;

While developing, it'll use the Mirrors-based encoding/decoding; but for publishing you can create a small transformer that will generate code.

Seth Ladd建立了此处的代码示例,我稍微扩展支持子对象:

Seth Ladd created a code sample here, which I extended slightly to support child-objects:

abstract class Serializable {
  static fromJson(Type t, Map json) {
    var typeMirror = reflectType(t);
    T obj = typeMirror.newInstance(new Symbol(""), const[]).reflectee;
    json.forEach((k, v) {
      if (v is Map) {
        var d = smoke.getDeclaration(t, smoke.nameToSymbol(k));
        smoke.write(obj, smoke.nameToSymbol(k), Serializable.fromJson(d.type, v));
      } else {
        smoke.write(obj, smoke.nameToSymbol(k), v);
      }
    });
    return obj;
  }

  Map toJson() {
    var options = new smoke.QueryOptions(includeProperties: false);
    var res = smoke.query(runtimeType, options);
    var map = {};
    res.forEach((r) => map[smoke.symbolToName(r.name)] = smoke.read(this, r.name));
    return map;
  }
}

目前,不支持获取通用类型信息(例如:支持List)在Smoke中;但我在这里提出了一个案例:

Currently, there is no support to get generic type information (eg. to support List) in Smoke; however I've raised a case about this here:

https://code.google.com/p/dart/issues/detail?id=20584

直到这个问题实现了,一个好的实现你想要的是不是真的可行;但我希望它会很快实施;因为做一些基本的,像JSON序列化的东西取决于它!

Until this issue is implemented, a "good" implementation of what you want is not really feasible; but I'm hopeful it'll be implemented soon; because doing something as basic as JSON serialisation kinda hinges on it!

这篇关于Dart JSON解码器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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