0
votes

I come across using ObjectMapper with String.class for first time.I tried giving json as string for which got JsonMappingException. Could you please help understand why?

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);
   }

Response:

Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token at [Source: {"response":"success"}; line: 1, column: 1] at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:270) at com.fasterxml.jackson.databind.DeserializationContext.reportMappingException(DeserializationContext.java:1234) at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1122) at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1075) at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:60) at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:11) at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3814) at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2858)

On just a trial when i pass response as "success", i get:

Exception in thread "main" com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'success': was expecting ('true', 'false' or 'null')

2

2 Answers

1
votes

Correct way is to read it as tree:

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

outputs: success

0
votes

Because you passed json pair where response is a field name and success is a value for this field so you need to create class ResponseDTO

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

and

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

Hope it helps.