简体   繁体   English

用Jackson将JSON展平为地图

[英]Flattening of json to a map with Jackson

I am currently using the Jackson library to unmarshal json to pojos, using annotations. 我目前正在使用Jackson库使用注释将json解组到pojos。

The json tree that I would like to unmarshal is as follows: 我想解组的json树如下:

{
    "key1":"value1",
    "key2":"value2",
    "key3":{
        "key31":{
            "key311":"value311",
            "key312":"value312",
            "key313":"value313"
        },
        "key32":"value32"
    },
    "key4":"value4",
    "key5":"value5",
    "key6":{
        "key61":"value61"
    }
}

I don't know the json structure in advance and would like to completely flatten it to a Map which content would be equivalent to: 我事先不知道json结构,想将其完全展平为Map,其内容等同于:

Map<String, Object> outputMap = new HashMap<String, Object>();
outputMap.put("key1", "value1");
outputMap.put("key2", "value2");
outputMap.put("key311", "value311");
outputMap.put("key312", "value312");
outputMap.put("key313", "value313");
outputMap.put("key32", "value32");
outputMap.put("key4", "value4");
outputMap.put("key5", "value5");
outputMap.put("key61", "value61");

(note that keys "key3", "key31" and "key6" should be ignored) (请注意,应忽略键“ key3”,“ key31”和“ key6”)

Using the annotation @JsonAnySetter , I can create a function to populate the map with all top level atoms, but the method will also catch the node having children (when the value is a Map). 使用注解@JsonAnySetter ,我可以创建一个函数来用所有顶级原子填充地图,但是该方法还将捕获具有子节点的节点(当值是Map时)。

From that point, I can of course write myself the simple recursion over the children, but I would like this part to be handled automatically (in an elegant way) through the use of a facility from the library (annotation, configuration, etc.), and not have to write the recursion by myself. 从这一点来看,我当然可以为自己编写关于子代的简单递归,但是我希望通过使用库中的功能(注释,配置等)自动(以一种优雅的方式)处理这一部分。 ,而不必自己编写递归。

Note: we assume there is not name clashing in the different level keys. 注意:我们假设不同级别的键中没有名称冲突。

There is no annotation-based mechanism to do this that I know of, since @JsonUnwrapped which might be applicable is only usable with POJOs, not Maps. 我不知道有基于注释的机制来执行此操作,因为可能适用的@JsonUnwrapped仅适用于POJO,不适用于Maps。 I guess you could file an enhancement request to ask @JsonUnwrapped to be extended to also handle Map case, although it seems only appicable for serialization (not sure how one could deserialize back). 我想您可以提出一个增强请求,要求将@JsonUnwrapped扩展为还处理Map情况,尽管这似乎仅适用于序列化(不确定如何反序列化)。

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

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