简体   繁体   English

从JSON映射到具有不同结构的Java对象

[英]Map from JSON to java object with different structure

I have a JSON string representing an object, and I want to put its information into a Java object B with a different structure. 我有一个表示对象的JSON字符串,我想将其信息放入具有不同结构的Java对象B Currently the solution I am taking is creating a Java Object A with a structure identical to the JSON object, made the conversion from JSON to A using Jackson and later, made the mapping from A to B using Dozer with XML mappings. 目前,我正在采用的解决方案是创建一个结构与JSON对象相同的Java对象A ,使用Jackson进行从JSON到A的转换, A使用带有XML映射的Dozer从AB映射。 Is there anyway to avoid having the A objects? 无论如何要避免使用A对象?

Making it short, currently I have this: 简而言之,目前我有这个:

JSON--Jackson-->A--Dozer(XML mappings)-->B

and I would like to achieve this 我想实现这一目标

JSON--???-->B

You may know this already, but Jackson can use loosely structure types like Map , or JsonNode as target, so you can do, say: 您可能已经知道这一点,但是Jackson可以使用MapJsonNode类的松散结构类型作为目标,因此您可以这样做:

JsonNode root = mapper.readTree(jsonSource); Map<String,Object> asMap = mapper.readValue(jsonSource, Map.class);

and then construct your B . 然后构造你的B Jackson has only limited amount of structural conversions (simple unwrapping), by design, although there is extensive set of scalar conversions (non-structural conversions), so if you do need structural changes it may make sense to use a library that is focused on structural changes. 通过设计,Jackson仅具有有限数量的结构转换(简单展开),尽管有大量标量转换(非结构转换),所以如果您确实需要结构更改,则可以使用专注于以下内容的库:结构变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM