杰克逊·JSON + Java 泛型
我正在尝试将以下 JSON 反序列化/映射到 List
{"bills":[{"amount":"13","billId":"billid3"}]}
这是我的转换方法:
private static void convert(){
String jsonBill = "{\"bills\":[{\"amount\":\"13\",\"billId\":\"billid3\"}]}";
ObjectMapper mapper = new ObjectMapper();
List<Bill> bills = null;
try {
bills = mapper.readValue(jsonBill, new TypeReference<List<Bill>>() { });
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("bills = " + bills.size());
}
Bill 实体如下:
@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS)
public class Bill {
private String amount;
private String billId;
public String getBillId() {
return billId;
}
public void setBillId(String billId) {
this.billId = billId;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
我收到此错误:
**org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.List out of START_OBJECT token
at [Source: java.io.StringReader@7a84e4; line: 1, column: 1]**
at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:160)
at org.codehaus.jackson.map.deser.StdDeserializationContext.mappingException(StdDeserializationContext.java:194)
at org.codehaus.jackson.map.deser.CollectionDeserializer.deserialize(CollectionDeserializer.java:103)
at org.codehaus.jackson.map.deser.CollectionDeserializer.deserialize(CollectionDeserializer.java:93)
at org.codehaus.jackson.map.deser.CollectionDeserializer.deserialize(CollectionDeserializer.java:25)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:1980)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1278)
这是我的简化 spring3 控制器,它返回 i/p json (使用 Jackson 映射)配置为默认视图):
@ModelAttribute("bills")
@RequestMapping(value = "/", method = RequestMethod.GET)
public List<Bill> fetchBills() throws IOException {
Bill bill = new Bill();
bill.setAmount("13");
bill.setBillId("billid3");
List<Bill> bills = new ArrayList<Bill>();
bills.add(bill);
return bills;
}
我想我错过了一些明显的东西..但不确定它是什么..有什么想法吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题不在于您的代码,而在于您的示例输入。您实际上要反序列化的是一个具有名为“bills”字段的对象,而不是一个列表!您应该用作输入的是:
这是一个对象数组,它被转换为一个列表。
The problem lies not in your code, but your example input. What you're actually trying to deserialize is an object with a field named "bills", not a list! What you should be using as input is:
This is an array of objects, which is converted to a list.
尝试使用 ObjectWriter 而不是 ObjectMapper
我正在使用 jackson 1.9.2
Try using ObjectWriter instead of ObjectMapper
I'm using jackson 1.9.2