Java + jackson parsing error Unrecognized character escape

余生长醉 提交于 2019-12-10 10:09:19

问题


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)

回答1:


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"}



回答2:


Set your mapper

mapper.configure(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true); 


来源:https://stackoverflow.com/questions/30187530/java-jackson-parsing-error-unrecognized-character-escape

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!