使用JSON-B 1.0(例如Yasson,Java EE 8)有效地将JsonObject转换为pojo

问题描述:

可以通过以下方式将JsonObject转换为其相应的类实例:

A JsonObject can be transformed into it's corresponding class instance via:

Pojo pojo = JsonbBuilder.create().fromJson(jsonObject.toString(), Pojo.class)

但是,使用jsonObject.toString()作为字符串是另一个包含相同信息的中间表示,似乎效率低下.我需要在对象绑定之前转换jsonObject.那么,有没有更有效的方法从JsonObject实现绑定?

However, it seems to be inefficient to use jsonObject.toString() as a String is an other intermediate representation, that contains the same information. I need to transform the jsonObject before the object binding. So is there a more efficient way to achieve the binding from a JsonObject?

(请注意,我想用Java EE 8标准实现,因此Gson和Jackson并不是一个选择,但可能是它的概念). Yasson 组中目前没有答案,所以希望有人能找到答案. Michael Schnell还提出了 JsonStructure 绑定,但目前尚无解决方案也是.

(Note I want to implement with Java EE 8 standards, so Gson and Jackson is not an option, but may be concepts of it). There is currently not answer in the Yasson group so hopefully, someone finds this. Michael Schnell also proposed a JsonStructure binding, but there is no solution yet too.

使用JSON-B 1.0标准无法转换JSON-P对象<-> POJO.但是,已经有足够多的人要求它,这肯定是我们将在下一版JSON-B中考虑的东西.

It is not possible with the JSON-B 1.0 standard to convert JSON-P object <--> POJO. However, enough people have asked for it that it's certainly something we will consider for the next version of JSON-B.

与此同时,转换为String或使用自定义适配器是您的最佳选择.

In the meantime, converting to String or using a custom adapter is your best option.

如果您担心JSON-B的性能,可以提高JSON-B性能的第一件事是缓存Jsonb的实例,即不要调用JsonbBuilder.create()每次您需要调用/fromJson时,因为所有注释扫描和类解析都是在创建Jsonb实例时进行的.

If you are concerned about performance with JSON-B, the #1 thing you can do to improve JSON-B performance is cache the instance of Jsonb, namely, don't call JsonbBuilder.create() each time you need to call to/fromJson, because all of the annotation scanning and class parsing happens upon creation of the Jsonb instance.

更新(2019年6月): 尽管仍然没有实现JSON-B的标准方法,但是JSON-B参考实现Eclipse Yasson在org.eclipse.yasson.YassonJsonb接口上添加了对此的支持. -ee4j/yasson/pull/262/files"rel =" nofollow noreferrer>此PR .希望此功能将包含在下一版JSON-B规范中.

Update (June 2019): Although there is still no JSON-B standard way of doing this, the JSON-B reference implementation, Eclipse Yasson, has added support for this on the org.eclipse.yasson.YassonJsonb interface in this PR. Hopefully this function will get included in the next version of the JSON-B spec.