【发布时间】:2020-05-19 09:43:31
【问题描述】:
我正在上以下课程:
public class Car{
private String id;
private String name;
public Car() {
}
public Car(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
我是这样使用它的:
String json = "{\"id\":\"1\", \"name\":\"hh\"} {\"id\":\"2\", \"name\":\"ccc\"}";
Car car;
try {
ObjectMapper mapper = new ObjectMapper();
car = mapper.readValue(json, new TypeReference<Car>() {
});
} catch (IOException e) {
car = null;
}
我预计它会失败,但相反,我得到了输入中的第一个对象,即“第一个”汽车对象。
为什么会这样?
【问题讨论】:
-
嘿,@YanKhonski 我知道我可以用数组来做到这一点。我的示例中的 json 参数实际上来自一个文件。我希望它有一个对象,但如果它有多个对象,我希望它失败。我更改了对象并删除了“,”仍然是第一个而不是失败
-
"{\"id\":\"1\", \"name\":\"hh\"} {\"id\":\"2\", \"name\":\"ccc\"}"json 无效,汽车对象之间缺少逗号 ,。 -
我知道并且我希望它会失败,但是 mapper.readValue 函数返回第一个对象并忽略第二个。在这个函数之后,汽车参数将保存 id = 1 & name -"hh"
-
请检查我的答案。抱歉来晚了。
标签: java json jackson objectmapper