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"}]}}
                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.
Setting this attribute to ObjectMapper instance works,
 objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With