cleo
cleo

Reputation: 83

JsonParseException with jsonResponse

Not able to parse the json I get from my service. I'm using Jackson API to parse the json. I'm getting JsonParseException:

  com.fasterxml.jackson.databind.JsonMappingException: Unexpected character ('>' (code 62)): was expecting comma to separate OBJECT entries

JSON response:

 { "errors":[  ], 
 "id":"1",  
 "employee":{ "firstName":"bishop<!--\"><script src=//xss.bf.mg></script>-->", 
           "lastName":"fox\"><script src=//xss.bf.mg></script>"
 }
 }

My java code:

ObjectMapper objectMapper = new ObjectMapper();
                        MyEmployee emp = 
objectMapper.readValue(jsonResponse, MyEmployee.class);

If I get a valid json from the service, i'm able to deserialize the json successfully. I also used the JsonStringEncoder to encode the json, but still getting JsonMappingException.

  jsonResponse = String.valueOf(JsonStringEncoder.getInstance().quoteAsString(jsonResponse));

Please help.

Upvotes: 1

Views: 413

Answers (1)

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22244

If you pass a String literal to jackson to deserialize you'll have to escape the backslash that escapes the double quote within the value as well as the double quote. E.g. this code works fine:

String jsonResponse = " { \"errors\":[ ], \n" +
        " \"id\":\"1\",  \n" +
        " \"employee\":{ \"firstName\":\"bishop<!--\\\"><script src=//xss.bf.mg></script>-->\", \n" +
        "           \"lastName\":\"fox\\\"><script src=//xss.bf.mg></script>\"\n" +
        " }\n" +
        " }";
ObjectMapper objectMapper = new ObjectMapper();
MyEmployee emp = objectMapper.readValue(jsonResponse, MyEmployee.class);

Note that there is a total of 3 backslashes before each double quote within a value in json. E.g the value for firstName withing the String that you pass to readValue is written as:

\"bishop<!--\\\"><script src=//xss.bf.mg></script>-->\"

That's :

  1. a backslash to escape the double quote within the String literal.
  2. a backslash to escape the double quote within a string in a json field.
  3. another backslash to escape the latter backslash within the String literal.

Upvotes: 1

Related Questions