杰克逊JSON + Java泛型

Rav*_*avi 15 java generics json jackson deserialization

我正在尝试List<Bill使用Jackson json库将以下JSON反序列化/映射到> java对象.(这个json是由杰克逊生成的,Iam为了简洁省略了那篇文章)

{"bills":[{"amount":"13","billId":"billid3"}]}
Run Code Online (Sandbox Code Playgroud)

这是我的转换方法:

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());
}
Run Code Online (Sandbox Code Playgroud)

该法案实体如下:

@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;
   } 
}
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

**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)
Run Code Online (Sandbox Code Playgroud)

这是我的简化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;
}
Run Code Online (Sandbox Code Playgroud)

我想我错过了一些明显的东西..但不确定它是什么..有什么想法吗?

Jas*_*ols 20

问题不在于您的代码,而在于您的示例输入.你实际上试图反序列化的是一个名为"bill"的字段的对象,而不是列表!您应该使用的输入是:

[{"billId":"billid3","amount":"13"}]
Run Code Online (Sandbox Code Playgroud)

这是一个对象数组,它被转换为一个列表.

  • 所以我需要将{"账单":[{"amount":"13","billId":"billid3"}}}转换为[{"billId":"billid3","金额":"13"}]在我的客户端.我正在寻找杰克逊包装方法,让我在没有任何自定义代码的情况下做到这一点. (2认同)