1
private static String tmp = "{\"data\":{\"vin\":\"LNBSCCAK9JD065606\",\"extParameter\":{\"systemTime\":\"2019-01-23 12:58:35\",\"fuelAmount\":20.0},\"pushType\":\"fuelWarn\"},\"type\":\"uaes-iot-public-service\"}";

public static void main(String[] args) {
    JSONObject jsonObject = JSON.parseObject(tmp);
    JSONObject data = JSON.parseObject(jsonObject.getString("data"));
    // line 1
    Map<String, String> result = (Map<String, String>) data.getInnerMap().get("extParameter");

    for (Map.Entry<String, String> item: result.entrySet()) {
        String key = item.getKey();
        // line 2
        String value = item.getValue();
    }
}

Above code throws a

ClassCastExecption at line 2: java.math.BigDecimal cannot be cast to java.lang.String

But the result type is acutally Map[String, String] , if the map's Value Type is not String, why is ClassCastExecption thrown at line 1?

2 Answers 2

2

The result type is only Map<String, String> because you have an unsafe cast that makes it such. There will have been a compiler warning about that.

The generic types exist only at compile-time, at run-time the Map does not check its component types.

String value = item.getValue();

Because of the generic types, the compiler believes that this Map only contains String, so you can write the above line. But what it actually compiles to is

String value = (String) item.getValue(); // cast inserted by compiler

and this will fail if the value happens to be something else.

"fuelAmount":20.0

This is not a String in JSON. You have to convert it to a String yourself (or handle other types of value being returned from the Map).

The best solution is probably to make some "bean" classes for the JSON parser to deserialize into. Those can have named and typed properties.

Sign up to request clarification or add additional context in comments.

Comments

0

Field "fuelAmount" is storing decimal values so the system is trying to convert your decimal to String that you are trying to cast so this will throw the error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.