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

问题描述 投票:0回答:2

我有一个 json 对象,其中包含值为

String
Double
Integer
的嵌套对象。当我转换为
Map
时,假设
Integer
Double
。我怎样才能改变这个?

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

我的回复包含以下字段

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

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

java json hashmap integer double
2个回答
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}

0
投票

您可以使用

GsonBuilder
setObjectToNumberStrategy
在 Gson 中配置此行为:

Gson gson = new GsonBuilder()
    .setObjectToNumberStrategy(LONG_OR_DOUBLE)
    .create();

byte[] data = gson.toJson(Map.of("id", 1)).getBytes(UTF_8);
Map<String, Object> map = gson.fromJson(new String(data, StandardCharsets.UTF_8), Map.class);

System.out.println(map);
© www.soinside.com 2019 - 2024. All rights reserved.