无法反序列化JSON中包含json字符串

gxwragnw  于 2023-03-04  发布在  其他
关注(0)|答案(2)|浏览(142)

我有一个如下的json,x是用来忽略敏感数据的

{"errormessage":"{\"timestamp\":\"2021-10- 19T07:57:35.205+0000\",\"status\":400,\"error\":\ "Bad Request\",\"message\":\"Bad Request: xxxx xxx xxx xxx xxx. path\u003d/xxx/verify\",\"path\":\"/xxx /xxx\"}"}

我正在尝试将此json反序列化到下面的类中

public class TransferResponse {

 private Optional<String> timeStamp = Optional.empty();
 private Optional<String> status = Optional.empty();
 private Optional<String> error = Optional.empty();

 @JsonAlias(value = {"errorMessage", "errormessage"})
 private Optional<String> message = Optional.empty();
 private Optional<String> path = Optional.empty();

}

下面给出了我尝试反序列化它的方法

final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new Jdk8Module());

final String nestedErrorResponse = "{\"errormessage\":\"{\"timestamp\":\"2021-10- 19T07:57:35.205+0000\",\"status\":400,\"error\":\"Bad Request\",\"message\":\"Bad Request: xxxx xx is xx xxx. path\u003d/xxx/xxx\",\"path\":\"/xxxx /xxx\"}\"}";

TransferResponse responseObject = objectMapper.readValue(nestedErrorResponse, TransferResponse.class);

但我得到了一个如下所示的异常

Unexpected character ('t' (code 116)): was expecting comma to separate Object entries
 at [Source: (String)"{"errormessage":"{"timestamp":"2021-10- 19T07:57:35.205+0000","status":400,"error":"Bad Request","message":"Bad Request: xxxx xx is xx xxx. path=/xxxxx/verify","path":"/xxxxx /xxxxx"}"}"; line: 1, column: 21]

我希望能够读取errormessage的值作为字符串。有人能帮助我吗?

k97glaaz

k97glaaz1#

当你以编程方式提供一个嵌套json的json字符串时,你需要转义斜杠--添加一个斜杠,然后立即转义它,这样嵌套的引号就有3个斜杠:

final String nestedErrorResponse = "{\"errormessage\":\"{\\\"timestamp\\\":\\\"2021-10- 19T07:57:35.205+0000\\\",\\\"status\\\":400,\\\"error\\\":\\\"Bad Request\\\",\"message\\\":\\\"Bad Request: xxxx xx is xx xxx. path\u003d/xxx/xxx\\\",\\\"path\":\\\"/xxxx /xxx\\\"}\"}";

我使用Intellij Idea,当我将一个json字符串复制到另一个字符串中时,它会自动添加适当数量的斜线。

dgtucam1

dgtucam12#

你可以转换你的JSON数据如下所示,并测试你的代码,希望这将帮助你解决这个问题.我通常测试我的JSON数据在线JSON数据验证器t. exhttps://jsonformatter.curiousconcept.com/#
“错误消息”:{“时间戳”:“2021-10- 19 T07:57:35.205+0000”,“状态”:400,“错误”:“错误请求”,“消息”:“错误请求:xxxx xxx xxx xxx.路径\u 003 d/xxx/验证”,路径”:“/xxx /xxx”}

相关问题