我有一个json对象,其中包含嵌套对象,其值分别为String
,Double
和Integer
。当我转换为Map
时,它假设Integer
为Double
。我该如何更改?
Map<String, Object> map = response.getJson();
我的回复中的字段为
{
....
"age" : 14,
"average" : 12.2,
....
}
average
已正确转换为Double
,但年龄预计为Integer
,但在converted
中为Double
至Map
>
答案 0 :(得分:0)
您可以通过对Map
进行后处理,在可能的情况下将Double
的值转换为Integer
来完成此操作,例如
static void convertIntegerToDouble(Map<String, Object> map) {
Map<String, Object> updates = new HashMap<>();
for (Iterator<Entry<String, Object>> iter = map.entrySet().iterator(); iter.hasNext(); ) {
Entry<String, Object> entry = iter.next();
Object value = entry.getValue();
if (value instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, Object> submap = (Map<String, Object>) value;
convertIntegerToDouble(submap);
} else if (value instanceof Double) {
double d = ((Double) value).doubleValue();
int i = (int) d;
if (d == i)
updates.put(entry.getKey(), i);
}
}
map.putAll(updates);
}
测试
Map<String, Object> map = new HashMap<>(Map.of(
"A", 42.0,
"B", new HashMap<>(Map.of(
"K", 42.0,
"L", new HashMap<>(Map.of(
"R", 42.0,
"S", 3.14
)),
"M", 3.14
)),
"C", 3.14,
"D", "Foo"
));
System.out.println(map);
convertIntegerToDouble(map);
System.out.println(map);
输出
{A=42.0, B={K=42.0, L={R=42.0, S=3.14}, M=3.14}, C=3.14, D=Foo}
{A=42, B={K=42, L={R=42, S=3.14}, M=3.14}, C=3.14, D=Foo}