javajsonjacksonhttp-postparse-error

Java + jackson parsing error Unrecognized character escape


I need to do a POST json string , using HttpClient. Following will be the code i have. From the other end the Json is mapped to an object.

HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
String jsonData = "{ \"provider\" : null , \"password\" : \"a\", \"userid\" : \"mlpdemo\\mlpdemoins\" }";
post.setEntity(new ByteArrayEntity(         jsonData.toString().getBytes("UTF8")));
HttpResponse response = client.execute(post);

Here all others are correctly mapping expect the userId. Here the problem is with the backward slash(mlpdemo\mlpdemins). I guess. If I send a single string as the user id it will be mapped without any issues. Eg:-

String jsonData = "{ \"provider\" : null , \"password\" : \"a\", \"userid\" : \"mlpdemoins\" }";

This works .

But I need this (mlpdemo\mlpdemins)to be sent through the POSt. Please help me out.

String jsonData = "{ \"provider\" : null , \"password\" : \"a\", \"userid\" : \"mlpdemo\\mlpdemoins\" }";

Here is the exception Im getting.

com.fasterxml.jackson.core.JsonParseException: Unrecognized character escape 'm' (code 109)
 at [Source: java.io.InputStreamReader@29f0a0a2; line: 1, column: 62]
BadRequestException (0ea35150-f33a-4932-a31e-8a1048af53ad): 400 Bad Request, com.strategicgains.restexpress.serialization.DeserializationException: com.fasterxml.jackson.core.JsonParseException: Unrecognized character escape 'm' (code 109)
 at [Source: java.io.InputStreamReader@29f0a0a2; line: 1, column: 62]
    at com.strategicgains.restexpress.Request.getBodyAs(Request.java:165)
    at com.strategicgains.restexpress.Request.getBodyAs(Request.java:181)

Solution

  • mlpdemo\mlpdemoins is an invalid string you can't use it in JSON . But you can use mlpdemo\\mlpdemoins easily.

    below code works fine for me :

    String jsonData = "{ \"provider\" : null , \"password\" : \"a\", \"userid\" : \"mlpdemo\\\\mlpdemoins\" }";
    
    ObjectMapper mapper=new ObjectMapper();
    
    System.out.println(mapper.readTree(jsonData));
    

    It will produce this output JSON :

    {"provider":null,"password":"a","userid":"mlpdemo\\mlpdemoins"}