Json 异常:Can not deserialize instance of xx out of START_ARRAY token

Server:

@RequestMapping(value = { "/hygiene/{phone}" }, method = {RequestMethod.POST },produces="application/json")
	@ResponseBody
	public PhoneResult hygiene(@PathVariable("phone")String phoneObject) {
		PhoneResult result = new PhoneResult();
		try {
			ObjectMapper mapper = new ObjectMapper();
			Phone phone = mapper.readValue(phoneObject, Phone.class);
			result.setRawPhoneNumber(phone.getPhoneNumber());
			result.setFormat("4+4+4");
			result.setCleanInternationalNumber("86 0513 23234442");
			result.setCleanNationalNumber("0513 23423423");
			result.setPreferredPresentation("513 234234234");
		}catch (Exception e) {
			e.printStackTrace();
			result.setCleanInternationalNumber("error");
		}
		
		return result;
	}

 

Client:

 

	MultiValueMap<String,Object> dataMap2 = new LinkedMultiValueMap<String, Object>();
		Phone p = new Phone();
		p.setPhoneNumber("0513 23423423");
		dataMap2.add("phone", JsonUtil.javaToJson(p));
		HttpEntity<Object> entity2 = new HttpEntity<Object>(dataMap2);  
		PhoneResult result = this.restTemplate.postForObject("http://localhost:8080/restServer/helloworld/hygiene/{phone}.spring", entity2,  PhoneResult.class, dataMap2);

 

public static String javaToJson(Object o) throws Exception{
		StringWriter writer = new StringWriter();
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(writer, o);
        String json=writer.toString();
        return json;
	}

 

 遇到的异常: server端转化json失败:

org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of com.pojo.Phone out of START_ARRAY token
 at [Source: java.io.StringReader@55afbf49; line: 1, column: 1]
	at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
	at org.codehaus.jackson.map.deser.StdDeserializationContext.mappingException(StdDeserializationContext.java:198)
	at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeUsingCreator(BeanDeserializer.java:565)
	at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:365)
	at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2391)
	at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1591)
	at com.acxiom.rest.controller.HelloWorldController.hygiene(HelloWorldController.java:52)

 

Debug了一下程序,发现传进来的json字符串是数组格式的:

[{"phoneNumber":"0513 XXXXX","phoneType":"1","countryCode":"1","geoOption":"1","defaultOption":"1","geoLat":"1","geoLong":"1"}]

 

果断修改了Server端代码:

 

	ObjectMapper mapper = new ObjectMapper();
	Phone phone = mapper.readValue(phoneObject, Phone[].class)[0];

 

问题解决。

 

 

 

你可能感兴趣的:(JsonToJAVA)