gpt4 book ai didi

java - Jackson json 映射和驼峰键名称

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:44:50 24 4
gpt4 key购买 nike

我想通过 jackson 库将 json 转换为包含 camelCase 键的 map ...比如说...

来自

{
"SomeKey": "SomeValue",
"AnotherKey": "another value",
"InnerJson" : {"TheKey" : "TheValue"}
}

为此...

{
"someKey": "SomeValue",
"anotherKey": "another value",
"innerJson" : {"theKey" : "TheValue"}
}

我的代码...

public Map<String, Object> jsonToMap(String jsonString) throws IOException
{
ObjectMapper mapper=new ObjectMapper();
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
return mapper.readValue(jsonString,new TypeReference<Map<String, Object>>(){});
}

但是这行不通...甚至其他propertyNamingStrategy在json上也行不通...比如...

{
"someKey": "SomeValue"
}

mapper.setPropertyNamingStrategy(new PropertyNamingStrategy.PascalCaseStrategy())

{
"SomeKey": "SomeValue"
}

如何通过 jackson 获取 camelCase Map key 名称...或者我应该手动循环 map 并转换 key 还是有其他方法???

提前致谢...

最佳答案

当您使用 map /字典而不是将 JSON 数据绑定(bind)到 POJO(与 JSON 数据匹配的显式 Java 类)时,属性命名策略不适用:

Class PropertyNamingStrategy ... defines how names of JSON properties ("external names") are derived from names of POJO methods and fields ("internal names")

因此,您必须先使用 Jackson 解析数据,然后遍历结果并转换 key 。

像这样更改您的代码:

public Map<String, Object> jsonToMap(String jsonString) throws IOException
{
ObjectMapper mapper=new ObjectMapper();
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
Map<String, Object> map = mapper.readValue(jsonString,new TypeReference<Map<String, Object>>(){});
return convertMap(map);
}

并添加这些方法:

public String mapKey(String key) {
return Character.toLowerCase(key.charAt(0)) + key.substring(1);
}

public Map<String, Object> convertMap(Map<String, Object> map) {
Map<String, Object> result = new HashMap<String, Object>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
result.put(mapKey(key), convertValue(value));
}
return result;
}

public convertList(Lst<Object> list) {
List<Object> result = new ArrayList<Object>();
for (Object obj : list) {
result.add(convertValue(obj));
}
return result;
}

public Object covertValue(Object obj) {
if (obj instanceof Map<String, Object>) {
return convertMap((Map<String, Object>) obj);
} else if (obj instanceof List<Object>) {
return convertList((List<Object>) obj);
} else {
return obj;
}
}

关于java - Jackson json 映射和驼峰键名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30727417/

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