[英]Unable to parse JSON with Jackson (mapping doesn't work)
我正在嘗試使用 Jackson 來解析示例 json,如下所示。 但是,我的解析不起作用(無任何例外地失敗 - 因為我得到一個空字符串 event.getAccountId(); 我做錯了什么?謝謝!
ObjectMapper om = new ObjectMapper();
String json = "{\"_procurementEvent\" : [{ \"accountId\" : \"3243234\",\"procurementType\" : \"view\"," +
"\"_procurementSubType\" : \"Standard Connector\",\"_quantity\" : \"4\", \"_pricePerMonth\" : \"100.00\"" +
",\"_annualPrice\" : \"1200.00\"}]}";
ProcurementEvent event = om.readValue(json, ProcurementEvent.class);
event.getAccountId(); // returns null
@JsonIgnoreProperties(ignoreUnknown = true)
private static class ProcurementEvent {
private String _accountId;
private String _procurementType;
private String _quantity;
private String _pricePerMonth;
private String _annualPrice;
@JsonProperty("accountId")
public String getAccountId() {
return _accountId;
}
public void setAccountId(String accountId) {
_accountId = accountId;
}
@JsonProperty("procurementType")
public String getProcurementType() {
return _procurementType;
}
public void setProcurementType(String procurementType) {
_procurementType = procurementType;
}
@JsonProperty("_quantity")
public String getQuantity() {
return _quantity;
}
public void setQuantity(String quantity) {
_quantity = quantity;
}
@JsonProperty("_pricePerMonth")
public String getPricePerMonth() {
return _pricePerMonth;
}
public void setPricePerMonth(String pricePerMonth) {
_pricePerMonth = pricePerMonth;
}
@JsonProperty("_annualPrice")
public String getAnnualPrice() {
return _annualPrice;
}
public void setAnnualPrice(String annualPrice) {
_annualPrice = annualPrice;
}
}
在問題中,嘗試以下方法:
class ProcurementEvents {
private List<ProcurementEvent> _procurementEvent; // + annotations like @JsonIgnoreProperties, getters/ setters, etc.
}
// json from your example
ProcurementEvents events = om.readValue(json, ProcurementEvents.class);
events.get(0).getAccountId();
您的代碼從json表示中反序列化ProcurementEvent
實例。 那里的問題是您的json表示string=>list of object representation
形式的映射string=>list of object representation
。 您可以使代碼工作不變,但是您需要編輯Json數據。 當json僅包含object representation
時,該示例將起作用。
將json數據修改為:
String json = "{ \"accountId\" : \"3243234\",\"procurementType\" : \"view\","
+ "\"_procurementSubType\" : \"Standard Connector\",\"_quantity\" : \"4\", "
+ "\"_pricePerMonth\" : \"100.00\",\"_annualPrice\" : \"1200.00\"}";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.