How to parse the dynamic JSON to JavaBean

Dennis Lee :

The JSON returned normally is like this

{"1":0.5}

However sometimes will return with mutipule key-value like

{
   "1":0.5,
   "2":0.5,
   "3":0.5
}

The content of JSON is dynamic. How to define the JavaBean to parse the JSON currectly. I parse the JSON using fastjson. Thanks for your kindly answering.

cassiomolin :

You can use a Map<K, V> for that and the Fastjson documentation provides an example on how to do it:

public static <K, V> Map<K, V> parseToMap(String json, Class<K> keyType, Class<V> valueType) {
    return JSON.parseObject(json, new TypeReference<Map<K, V>>(keyType, valueType) {});
}

Then use:

String json = ...
Map<String, BigDecimal> map = parseToMap(json, String.class, BigDecimal.class);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=206299&siteId=1