Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception: "org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token"

Tags:

java

json

jackson

I am trying to validate a simple JSON body using Jackson, where I am storing the JSON request as a String in "dataJson" variable.

public void unmarshal(InputStream is) throws Exception {
// this will contain my actual json string
  String dataJson= StUtil.toString(is);
  System.out.println(dataJson);

  //parse json string    
  String response = objectMapper.readValue(dataJson, String.class);
  System.out.println(response);
}

SUtil.toString(InputStream is) method:

 public static String toString(final InputStream is) {
    final BufferedReader br = new BufferedReader(new InputStreamReader(is));
    final StringBuffer buffer = new StringBuffer();
    try {
       for (String line; (line = br.readLine()) != null; ) {
          buffer.append(line);
           }
        } catch (IOException ioe) {
        }
      return buffer.toString();
   }

I am learning the validation part using Jackson but it throws error/exception on line

String response = objectMapper.readValue(dataJson, String.class);

And below is the exception I am getting -

Exception: "org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token"

I wanted to learn what wrong am I doing. Any help on this would be appreciated.

JSON Request:

{"username" : "my_username","password" : "my_password","validation-factors":{"validationFactors":[{"name":"remote_address","value":"127.0.0.1"}]}}
like image 765
AKIWEB Avatar asked Oct 21 '14 23:10

AKIWEB


2 Answers

A JSON String maps to a Java String (and vice versa), but a JSON object does not map to a Java String, which is what you are trying to do with readValue.

If you're simply trying to validate the JSON, use something like

objectMapper.readTree(dataJson);

and ignore the result. The call will have thrown an exception if it failed to parse.

like image 92
Sotirios Delimanolis Avatar answered Nov 06 '22 10:11

Sotirios Delimanolis


Setting this attribute to ObjectMapper instance works,

 objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
like image 2
Rupesh Kumar Avatar answered Nov 06 '22 10:11

Rupesh Kumar