无法用Jackson解析JSON(映射不起作用)

问题描述 投票:0回答:2

我正在尝试使用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;
        }
    }
java json parsing jackson
2个回答
1
投票

在问题中,请尝试以下方法:

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();

0
投票

您的代码从json表示反序列化ProcurementEvent的实例。问题是你的json代表映射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\"}";

© www.soinside.com 2019 - 2024. All rights reserved.