无法从START_OBJECT令牌String.class中反序列化java.lang.String实例

时间:2018-09-03 10:34:27

标签: java json jackson

我第一次遇到将ObjectMapper与String.class一起使用。我尝试将json作为字符串提供给JsonMappingException。您能帮忙了解一下原因吗?

public static void main(String args[]) throws JsonParseException, JsonMappingException, IOException{
       String response="{\"response\":\"success\"}";
       ObjectMapper objectMapper = new ObjectMapper();
        Object object = objectMapper.readValue(response, String.class);
        System.out.println(object);
   }

响应:

  

线程“主”中的异常   com.fasterxml.jackson.databind.JsonMappingException:无法   在START_OBJECT令牌中反序列化java.lang.String实例   [来源:{“响应”:“成功”};行:1,列:1]在   com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:270)     在   com.fasterxml.jackson.databind.DeserializationContext.reportMappingException(DeserializationContext.java:1234)     在   com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1122)     在   com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1075)     在   com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:60)     在   com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:11)     在   com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3814)     在   com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2858)

仅当我通过“成功”响应时,我得到:

  

线程“主”中的异常   com.fasterxml.jackson.core.JsonParseException:无法识别的令牌   '成功':正在期待('true','false'或'null')

2 个答案:

答案 0 :(得分:1)

正确的方法是转到read it as tree

ObjectMapper om = new ObjectMapper();
JsonNode tree = om.readTree("{\"response\":\"success\"}");
String response = tree.get("response").asText();
System.out.println(response);

输出: success

答案 1 :(得分:0)

因为您传递了json对,其中response是一个字段名,成功是该字段的值,所以您需要创建类ResponseDTO

public class ResponseDto { private String response; //getter/setter here

 Object object = objectMapper.readValue(response, ResponseDTO.class);

希望有帮助。