jackson解析错误无法识别的字符转义

jackson解析错误无法识别的字符转义

本文介绍了Java + jackson解析错误无法识别的字符转义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用HttpClient来做一个POST json字符串。以下将是我的代码。从另一端,Json被映射到一个对象。

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);

这里所有其他人都正确映射期望userId。这里的问题是反斜杠( mlpdemo \ mlpdemins )。我猜。如果我发送一个字符串作为用户ID,它将被映射而没有任何问题。
例如: -

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

这样做。

但我需要这个( mlpdemo \ mlpdemins )将通过POSt发送。请帮帮我。

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)


推荐答案

mlpdemo \ mlpdemoins 是一个无效的字符串,你不能在JSON中使用它。但你可以轻松地使用 mlpdemo \\mlpdemoins

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));

它将产生此输出JSON:

It will produce this output JSON :

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

这篇关于Java + jackson解析错误无法识别的字符转义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 23:09