[Solved] fastjson Error: com.alibaba.fastjson.JSONObject cannot be cast to xxxx

There is a StockData object. Normally, the JSON string to object should be:

StockData stockData = JSONObject.parseObject(str, StockData.class);

However, if the object is a generic (e.g. StockData<StockDetail>), it can be converted as above, but StockDetail throws an exception when it gets the object parameters via get com.alibaba.fastjson. JSONObject cannot be cast to cn.seagen.sorting.bean.StockDetail.

StockData<StockDetail> stockData = JSONObject.parseObject(str, StockData.class);

prompt JSONObject can not be converted to StockDetail object, the reason is probably.

fastjson conversion json object encounters a generic, it will not be correctly converted to a generic object, the converted object is a JSONObject object, not the object inside the generic, so there is also the above-thrown exception.


In addition to the above methods, fastjson also overloads a method.

public static <T> T parseObject(String text, TypeReference<T> type, Feature... features){}

Therefore, when the string is converted to a generic object, it is OK to use TypeReference for conversion. After conversion, StockDetail can normally get the parameter value of the object.

StockData<StockDetail> stockData = JSONObject.parseObject(str, new TypeReference<StockData<StockDetail>>(){});

Read More: