无法使用Jackson解析JSON(映射无效)

时间:2018-09-15 19:51:38

标签: java json parsing jackson

我正尝试使用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;
        }
    }

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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\"}";