先描述下问题:
1、在写junit单元测试用例时,返回的json串转为java对象时不成功!出现错误提示
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.xx.xx.modules.bd.entity.xx.xx。
2、经过debug,发现对象属性全部都自动转为LinkedHashMap了,
content值为:{"statusCode":200,"msg":"成功返回","obj":[{"id":"41","isNewRecord":false,"remarks":"","createDate":"2016-08-28 09:03:52","updateDate":"2016-08-28 09:03:52","xxList":[],"xx":"","xx":"","xx":"","xx":"01","xx":"1","xx":45,"xxList":[]}]}
如图:
3、JsonResp 代码:
package com.xxx.xxx.common.json; import java.io.Serializable; /** * json 返回 * Created by weimingjia on 2016/7/10. */ public class JsonResp implements Serializable{ private int statusCode = 200; //状态码 private String msg; private Object obj; public JsonResp(){} public JsonResp(int statusCode,String msg){ this.statusCode = statusCode; this.msg = msg; } public JsonResp(int statusCode,String msg,Object obj){ this.statusCode = statusCode; this.msg = msg; this.obj = obj; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Object getObj() { return obj; } public void setObj(Object obj) { this.obj = obj; } public int getStatusCode() { return statusCode; } public void setStatusCode(int statusCode) { this.statusCode = statusCode; } }
4、jsonMapper代码:
/** * Copyright © 2012-2014 JeeSite All rights reserved. */ package com.xxx.xxx.common.mapper; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.TimeZone; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonParser.Feature; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.util.JSONPObject; import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule; import com.google.common.collect.Lists; import com.google.common.collect.Maps; /** * 简单封装Jackson,实现JSON String<->Java Object的Mapper. * 封装不同的输出风格, 使用不同的builder函数创建实例. * @author ThinkGem * @version 2013-11-15 */ public class JsonMapper extends ObjectMapper { private static final long serialVersionUID = 1L; private static Logger logger = LoggerFactory.getLogger(JsonMapper.class); private static JsonMapper mapper; public JsonMapper() { this(Include.NON_NULL); } public JsonMapper(Include include) { // 设置输出时包含属性的风格 if (include != null) { this.setSerializationInclusion(include); } // 允许单引号、允许不带引号的字段名称 this.enableSimple(); // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性 this.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // 空值处理为空串 this.getSerializerProvider().setNullValueSerializer(new JsonSerializer
5、单元测试用例代码:
package com.xxx.xxx.xx.xxx.xx.xx; import com.google.common.reflect.Reflection; import com.xxx.xxx.common.json.JsonResp; import com.xxxx.xxx.modules.bd.entity.prescription.PactsPrescription; import com.xxxx.xxx.modules.bd.entity.prescription.PactsTemplate; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.junit.Test; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MvcResult; import java.util.ArrayList; import java.util.List; import java.util.Map; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.number.OrderingComparison.greaterThan; import static org.junit.Assert.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Created by weimingjia on 16-8-27. */ public class PactsPrescriptionRestControllerTest extends PactsTemplateRestControllerTest{ private String path = "/xxx/xx/xx/rest"; @Test public void testGetPactsPrescriptionByTemplateId() throws Exception { Object id = getAddResponseContent(); assertNotNull("xxx id is null",id); assertNotSame("xxx id is empty","",id); logger.info("xxx id is "+id); String pactsTemplateJsonAdd = String.format(pactsTemplateJson, id); PactsTemplate pactsTemplate = jsonMapper.fromJson(pactsTemplateJsonAdd,PactsTemplate.class); System.out.println(pactsTemplate); ListprescriptionListCorrect = pactsTemplate.getPrescriptionList(); assertNotNull("根据json文件读取xx模板 is null",prescriptionListCorrect); assertThat("根据json文件读取xx模板,xx集合 is empty",prescriptionListCorrect.size(),greaterThan(0)); PactsPrescription pactsPrescriptionCorrect = prescriptionListCorrect.get(0); MvcResult mvcResult= this.mockMvc.perform(get(path+"/byPactsTemplate/"+id.toString())) .andDo(print()) .andExpect(jsonPath("$.statusCode").value(200)) .andExpect(jsonPath("$.obj").value(is(instanceOf(List.class)))).andReturn(); String content = mvcResult.getResponse().getContentAsString(); System.out.println(content); // JSONObject jsonobject = JSONObject.fromObject(content); // JSONArray array = jsonobject.getJSONArray("obj"); // List prescriptionList = new ArrayList (); // for (int i = 0; i < array.size(); i++) { // JSONObject object = (JSONObject)array.get(i); // PactsPrescription passport = (PactsPrescription)JSONObject.toBean(object, // PactsPrescription.class); // if(passport != null){ // prescriptionList.add(passport); // } // } JsonResp jsonResp = jsonMapper.fromJson(content,JsonResp.class); System.out.println(jsonResp.getObj()); List prescriptionList = (List )jsonResp.getObj(); assertNotNull("根据xx模板id获取xx集合 is null",prescriptionList); assertThat("根据xx模板id获取xx集合 is empty",prescriptionList.size(),greaterThan(0)); PactsPrescription pactsPrescription = prescriptionList.get(0); assertThat("处方名称不一致",pactsPrescription.getPrescriptionName(),equalTo(pactsPrescriptionCorrect.getPrescriptionName())); assertThat("处方类型不一致",pactsPrescription.getPrescriptionType(),equalTo(pactsPrescriptionCorrect.getPrescriptionType())); } }
解决方式一:
1、引入jar包:
<dependency> <groupId>com.hynnetgroupId> <artifactId>json-libartifactId> <version>2.4version> dependency>
2、将以下代码注释打开:
// JSONObject jsonobject = JSONObject.fromObject(content); // JSONArray array = jsonobject.getJSONArray("obj"); // ListprescriptionList = new ArrayList (); // for (int i = 0; i < array.size(); i++) { // JSONObject object = (JSONObject)array.get(i); // PactsPrescription passport = (PactsPrescription)JSONObject.toBean(object, // PactsPrescription.class); // if(passport != null){ // prescriptionList.add(passport); // } // }
同时,注释以下代码:
JsonResp jsonResp = jsonMapper.fromJson(content,JsonResp.class); System.out.println(jsonResp.getObj()); ListpxxList = (List )jsonResp.getObj();
至此,完成!debug如图:
解决方式二:
ObjectMapper objectMapper = new ObjectMapper(); JsonNode rootNode = objectMapper.readTree(content); JsonNode objNode=rootNode.get("obj"); String json = objectMapper.writeValueAsString(objNode); JavaType javaType = objectMapper.getTypeFactory().constructParametricType( List.class, xxx.class); ListprescriptionList=objectMapper.readValue(json,javaType);
这种方式好处:不用重新引入新的json包,还是使用
import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper;