如何将json转换为Map <String,Object>以确保整数将为Integer

时间:2019-08-07 00:52:26

标签: java json hashmap integer double

我有一个json对象,其中包含嵌套对象,其值分别为StringDoubleInteger。当我转换为Map时,它假设IntegerDouble。我该如何更改?

Map<String, Object> map = response.getJson();

我的回复中的字段为

{
    ....
    "age" : 14,
    "average" : 12.2,
    ....
}

average已正确转换为Double,但年龄预计为Integer,但在converted中为DoubleMap

1 个答案:

答案 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}