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

标签 java json hashmap integer double

我有一个 json 对象,其中包含值为 String 的嵌套对象, DoubleInteger 。当我转换为Map时,假设IntegerDouble 。我该如何改变这个?

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

我的回复包含字段

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

average正在正确转换为 Double但年龄预计为 Integer但正在convertedDoubleMap

最佳答案

您可以通过对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}

关于java - 如何将 json 转换为 Map<String, Object> 确保整数为 Integer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57385656/

相关文章:

java - 为什么我的按钮在我的 JFrame 中不可见?

json - 如何通过Flutter中的共享首选项将Text Input数据以json格式保存在本地?

java - 创建一个 JSONArray

java - 将 HashMap 的 ArrayList 转换为 JSON String

java - 将编码开关传递给 Gradle "JavaExec"任务的 JVM

java.lang.reflect.InaccessibleObjectException : Unable to make field private final java. lang.Object java.util.Optional.value 可访问:

java - 显示点击的特定链接的数据

php - 列出 JSON 数组

java - 使用字符串和列表 bean 作为参数对 TreeMap 中的值进行排序

java - HashMap replace 和 put 的区别