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

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

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

However, if the article is a generic (e.g. StockData<StockDetail>), it may well be transformed as above, however StockDetail throws an exception when it will get the article parameters by way of get com.alibaba.fastjson. JSONObject cannot be cast to cn.seagen.sorting.bean.StockDetail.

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

immediate JSONObject can’t be transformed to StockDetail object, the reason being most likely.

fastjson conversion json object encounters a generic, it is not going to be accurately transformed to a generic object, the transformed object is a JSONObject object, not the article contained in the generic, so there may be additionally the above-thrown exception.

Solution

In addition to the above strategies, fastjson additionally overloads a way.

public static <T> T parseObject(String textual content, TypeReference<T> sort, Feature... options){}

Therefore, when the string is transformed to a generic object, it’s OK to use TypeReference for conversion. After conversion, StockDetail can usually get the parameter worth of the article.

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

Leave a Reply

Your email address will not be published. Required fields are marked *