简体   繁体   中英

How to convert json to Map<String, Object> making sure integers will be Integer

I have a json object which contains nested objects with values as String , Double and Integer . When I convert to Map , its assuming Integer as Double . How can I change this ?

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

my response has fields as

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

average is being converted properly into Double but age is expected as an Integer but being converted to Double in Map

You can do it by post-processing the Map , to convert Double values to Integer where possible, eg

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);
}

Test

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);

Output

{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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM