我该如何做数据对象的自动数据序列化? [英] How do I do automatic data serialization of data objects?

查看:106
本文介绍了我该如何做数据对象的自动数据序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有某种反射/内省特性的语言的巨大优势之一是可以从各种来源自动构建对象。例如,在Java我可以使用相同的对象来持久化到数据库(使用Hibernate),序列化到XML(使用JAXB)和序列化到JSON(json-lib)。您可以在Ruby和Python中执行相同的操作,通常遵循一些关于Java的属性或注释的简单规则。

因此我不需要大量的域转移对象。我可以专注于我工作的领域。



看起来像非常严格的FP,像Haskell和Ocaml这是不可能的。
特别是Haskell。我所看到的唯一的事情就是做一些预处理或元编程(ocaml)。是否接受你必须从底部向上进行所有转换?



换句话说,你必须做很多无聊的工作来转换haskell中的数据类型到一个JSON / XML / DB Row对象,然后再返回到一个数据对象。

解决方案

在OCaml中找到的预处理器解决方案(以sexplib,binprot和json-wheel等为例)非常棒(我认为人们使用Template Haskell做了非常类似的事情)。它比反射效率更高,也可以以自然的方式适应各种类型。如果您不喜欢给定类型foo的自动生成序列化程序,那么您可以随时编写自己的序列化程序,并且它非常适合包含foo作为组件的类型的自动生成序列化程序。



唯一的缺点是你需要学习camlp4为自己写一个。但使用它们非常容易,一旦你的生成系统设置为使用预处理器。就像在类型定义的末尾添加和sexp 一样简单:

  type t = {foo:int; bar:float} 
with sexp

现在你有了你的序列化器。


One of the huge benefits in languages that have some sort of reflection/introspecition is that objects can be automatically constructed from a variety of sources.

For example, in Java I can use the same objects for persisting to a db (with Hibernate), serializing to XML (with JAXB), and serializing to JSON (json-lib). You can do the same in Ruby and Python also usually following some simple rules for properties or annotations for Java.

Thus I don't need lots "Domain Transfer Objects". I can concentrate on the domain I am working in.

It seems in very strict FP like Haskell and Ocaml this is not possible. Particularly Haskell. The only thing I have seen is doing some sort of preprocessing or meta-programming (ocaml). Is it just accepted that you have to do all the transformations from the bottom upwards?

In other words you have to do lots of boring work to turn a data type in haskell into a JSON/XML/DB Row object and back again into a data object.

解决方案

For what it's worth, I think the pre-processor solution found in OCaml (as exemplified by sexplib, binprot and json-wheel among others) is pretty great (and I think people do very similar things with Template Haskell). It's far more efficient than reflection, and can also be tuned to individual types in a natural way. If you don't like the auto-generated serializer for a given type foo, you can always just write your own, and it fits beautifully into the auto-generated serializers for types that include foo as a component.

The only downside is that you need to learn camlp4 to write one of these for yourself. But using them is quite easy, once you get your build-system set up to use the preprocessor. It's as simple as adding with sexp to the end of a type definition:

type t = { foo: int; bar: float }
with sexp

and now you have your serializer.

这篇关于我该如何做数据对象的自动数据序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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