gpt4 book ai didi

java - 将 JSON 反序列化为 Map,并为每个属性提供回调

转载 作者:行者123 更新时间:2023-12-02 08:52:04 29 4
gpt4 key购买 nike

我想将任意 JSON 反序列化为 Map<String, Object> 。该映射的值可以是一些原语(例如 IntegerStringLocalDate 、...)或另一个 Map<String, Object> (递归)。

要获取原语,应该为每个属性调用某种自定义客户端回调。根据 key 的不同,将会发生某些反序列化。例如(伪代码):

{
"name": "Bill",
"age": 53,
"timestamp": "2012-04-23T18:25:43.511Z",
"coordinates": "51.507351;-0.127758",
"address": {
"street": "Wallstreet",
"city": "NY"
}
}

Object convert(key, value) {
if ("name".equals(key)) {
return value.toString();
} else if ("timestamp".equals(key)) {
return LocalDate.parse(value);
} else if ("coordinates".equals(key)) {
return Coordinates.parse(value);
}
...
}

在SO Jackson - Recursive parsing into Map<String, Object>提供了一个简单的通用解决方案。但是,这只是将每个非对象属性反序列化为 String 。是否可以将自定义客户端回调(如上所示)添加到反序列化过程中?

最佳答案

开箱即用:

new ObjectMapper.readValue("\"name\": ...", Map.class);

Jackson 将示例中的输入转换为:

class java.util.LinkedHashMap(
name -> class java.lang.String(Bill),
age -> class java.lang.Integer(53),
address -> class java.util.LinkedHashMap(
street -> class java.lang.String(Wallstreet),
city -> class java.lang.String(NY)
)
)

如果您想要一些自定义处理(例如,您想要 BigInteger 而不是年龄的整数),您可以使用自定义 LinkedHashMap 实现,例如:

public class CustomMap extends LinkedHashMap<String, Object> {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

private Object convertPrimitive(String key, Object value) {
switch (key) {
case "age":
return new BigInteger(value.toString());
case "city":
return value.toString().toLowerCase();
default:
return value;
}
}

private Object convertMap(String key, Object value) {
return OBJECT_MAPPER.convertValue(value, CustomMap.class);
}

@Override
public Object put(String key, Object value) {
return super.put(key, (value instanceof Map) ? convertMap(key, value) : convertPrimitive(key, value));
}
}

这一次,

new ObjectMapper.readValue("\"name\": ...", CustomMap.class);

将导致:

class org.example.CustomMap(
name -> class java.lang.String(Bill),
age -> class java.math.BigInteger(53),
address -> class org.example.CustomMap(
street -> class java.lang.String(Wallstreet),
city -> class java.lang.String(ny)
)
)

关于java - 将 JSON 反序列化为 Map<String, Object>,并为每个属性提供回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34642800/

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