【问题标题】:Map nested JSON list to Object array in Spring Boot with Jackson [duplicate]使用Jackson将嵌套的JSON列表映射到Spring Boot中的对象数组[重复]
【发布时间】:2021-09-29 03:56:25
【问题描述】:

This is the form of my response JSON.

顶层是一个列表,但我真正关心的对象在“结果”列表中,which here is an example of one of them expanded (they are maps). 每个“结果”基本上是一个配方和与该配方有关的信息。我目前正在做:

ObjectMapper mapper = new ObjectMapper();
Recipe[] recipes = mapper.readValue(json, Recipe[].class);

但它在第一个字符上失败:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type [Lcom.prepchef.backend.Recipe; from Object value (token JsonToken.START_OBJECT) at [Source: (StringReader); line: 1, column: 1]

我猜是因为“结果”部分不是 JSON 的顶级。但我不确定如何修改 readValue 方法来隔离“结果”部分。

我非常感谢有关此主题的任何建议。

【问题讨论】:

标签: java spring jackson objectmapper


【解决方案1】:

This stackoverflow post was helpful. 使用 JsonNode 的 at() 方法,我能够指定“结果”,就好像它是顶级:

ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(spoonacularResponse.body());
String sourceString = jsonNode.at("/results").toString();
Recipe[] recipes = mapper.readValue(sourceString, Recipe[].class);

【讨论】:

    猜你喜欢
    • 2019-04-19
    • 2017-03-06
    • 2018-03-17
    • 2020-07-19
    • 2015-05-07
    • 2016-07-13
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    相关资源
    最近更新 更多