gpt4 book ai didi

java - Jackson:如何将平面 json 转换为嵌套 json

转载 作者:行者123 更新时间:2023-12-02 12:00:30 24 4
gpt4 key购买 nike

如何转换 json 字符串

{
"a.b": 1,
"a.c.d": 2
}

转换成json字符串

{
"a": {
"b": 1,
"c": {
"d": 2
}
}
}

通过使用ObjectMapper

最佳答案

最简单的选择是创建自定义反序列化器或使用 @JsonAnySetter@JsonAnyGetter 自定义反序列化器,以下是示例:

public static final String json = "{\"a.b\": 1,\"a.c.d\": 2}";
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
HelperBean bean = mapper.readValue(json, HelperBean.class);
System.out.println(mapper.writeValueAsString(bean));
// result: {"a":{"b":1,"c":{"d":2}}}
}
public static class HelperBean{
@JsonIgnore
private Map<String, Object> data = new TreeMap<>();

@JsonAnySetter
public void setDays(String key, Object value){
String[] parts = key.split("\\.");
Map<String, Object> currMap = data;
for (int i = 0; i< parts.length; i++){
String part = parts[i];
Object subMap = currMap.get(part);
if (i == parts.length - 1) // last node
currMap.put(part, value);
else if(subMap == null){ // new node
subMap = new TreeMap<>();
currMap.put(part, subMap);
currMap = (Map<String, Object>) subMap;
}else if (subMap instanceof Map){ // existing node
currMap.put(part, subMap);
currMap = (Map<String, Object>) subMap;
} else { // node conflict
// handle exception when a.b = 1 and a.b.c = 1
}
}
}
@JsonAnyGetter
public Map<String, Object> getData() {
return data;
}
}

关于java - Jackson:如何将平面 json 转换为嵌套 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47283856/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com