有一个函数返回 JSON 格式的元素列表。从包含后代类型元素的结果中读取内容时出现问题。
例如,考虑以下定义:
public class Fruits {
public String description;
public List<Fruit> fruits = new ArrayList<Fruit>();
}
public class Fruit {
public String name;
public int pieces;
}
public class Banana extends Fruit {
public String origin;
}
@ApplicationScoped
@Provider
@Produces("application/json")
@Path("/fruit")
public class MyRestService {
@GET
@Path("/fruits")
public Fruits getFruits() {
Fruits myFruits = new Fruits();
myFruits.description = "My fruits";
Fruit myApple = new Fruit();
myApple.name = "apple";
myApple.pieces = 8;
myFruits.fruits.add(myApple);
Banana myBanana = new Banana();
myBanana.name = "banana";
myBanana.pieces = 5;
myBanana.origin = "Ecuador";
myFruits.fruits.add(myBanana);
return myFruits;
}
}
生成的 JSON 如下:
{
"description":"My fruits",
"fruits":[
{
"name":"apple",
"pieces":8
},
{
"name":"banana",
"pieces":5,
"origin":"Ecuador"
}
]
}
假设我们在 content
变量中有这个结果。我想按如下方式解析它:
ObjectMapper objectMapper = new ObjectMapper();
Fruits fruits = objectMapper.readValue(content, Fruits.class);
抛出以下异常:
Exception in thread "main" org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "origin" (Class myresttest.Fruit), not marked as ignorable
at [Source: java.io.StringReader@38653ad5; line: 1, column: 104] (through reference chain: myresttest.Fruits["fruits"]->myresttest.Fruit["origin"])
是否有可能在不接触服务器代码的情况下解决这个问题?
最佳答案
我建议你使用json-simple-1.1.1
您可以像这样获取 JSonObject :
JSONObjec requestobj = (JSONObject) JSonValue.parse(request) ;
Note: request value should be a String representation of the JSON .
然后将 requestobj 字段解析为一个新的 Fruits 实例...... 例如:
Fruits myFruits = new Fruits();
myFruits.description = (String) requestobj.getString("description");
关于java - 解析具有后代元素的 JSON 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36735144/