将嵌套的 JSON 列表映射到 Spring Boot with Jackson 中的对象数组
Map nested JSON list to Object array in Spring Boot with Jackson
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 方法以隔离“结果”部分。
如果有任何关于这个问题的建议,我将不胜感激。
使用 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);
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 方法以隔离“结果”部分。
如果有任何关于这个问题的建议,我将不胜感激。
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(spoonacularResponse.body());
String sourceString = jsonNode.at("/results").toString();
Recipe[] recipes = mapper.readValue(sourceString, Recipe[].class);