java.util.LinkedHashMap cannot be cast to com.xxx

问题描述:

接收json格式为:

{
	"attributes": {},
	"dataItems": [{
		"attributes": {
			"cardNo": "",
			"isOut": "1",
			"inOperator": "Admin",
			"carNo": "浙-*****",
			"parkName": "马赛克",
			"inTime": "2018-01-12 09:22:31",
			"inEventType": "",
			"inEquip": "6楼87号入口",
			"cardType": "临时车A",
			"parkCode": "0000007796"
		},
		"failItems": [],
		"objectId": "",
		"operateType": "READ",
		"subItems": []
	        }],
        "resultCode": 0,
	"seqId": "-983v_4cbn",
	"serviceId": "3c.park.queryparkinrecord"
}


接收的对象为:

public class JHTResult {
   // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();
    //服务标识
    private String serviceId;
    //返回码0:成功,1:未知错误,2:参数不正确
    private Integer resultCode;
    private String seqId;
    private Object attributes;
    private String message;

    private List dataItems;
   //省略get set 
}
其中:JHTDataItemsResult.java为:

public class JHTDataItemsResult {
	//子对象ID
	private String objectId;
	//子对象操作类型,固定值传入:READ
	private String operateType;
	//返回结果值对象
	private E attributes;
	
	private List failItems;
	
	private List subItems;
//省略get set
}
当将json转化为JHTResult时,获取attributes属性时
JHTVehicleRecordData resultVo = (JHTVehicleRecordData) attributes;

报以下错误:

java.util.LinkedHashMap cannot be cast to com.*****.park.model.vo.JHTVehicleRecordData

解决方法:先将对象转为json字符串,再根据ObjectMapper类的readValue()方法转化为对应class的类对象

JHTVehicleRecordData resultVo = JsonUtils.conveterObject(attributes, JHTVehicleRecordData.class);

其中JsonUtils.java为:

public class JsonUtils {

	/**
	 * 

* 对象转JSON字符串 *

*/ public static String object2Json(Object obj) { String result = null; try { ObjectMapper objectMapper = new ObjectMapper(); result = objectMapper.writeValueAsString(obj); } catch (IOException e) { e.printStackTrace(); } return result; } public static Map object2Map(Object obj) { String object2Json = object2Json(obj); Map result = jsonToMap(object2Json); return result; } /** *

* JSON字符串转Map对象 *

*/ public static Map jsonToMap(String json) { return json2Object(json, Map.class); } /** *

* JSON转Object对象 *

* */ public static T json2Object(String json, Class cls) { T result = null; try { ObjectMapper objectMapper = new ObjectMapper(); result = objectMapper.readValue(json, cls); } catch (IOException e) { e.printStackTrace(); } return result; } public static T conveterObject(Object srcObject, Class destObjectType) { String jsonContent = object2Json(srcObject); return json2Object(jsonContent, destObjectType); } }











你可能感兴趣的:(JSON和XML,java面试)