反序列化 json 对象的嵌套数组 returns null

Deserialize nested array of json object returns null

我的 Json 看起来像(并且不可修改)

{
    ....
    "Sale": [
        { "SaleLines": {
                    "SaleLine": [
                        {
                            "unitPrice": "190",
                            "unitQuantity": "1"
                        } 
                ], 
            "calcDiscount": "0",
            "calcSubtotal": "500"
        }
    } ]
}

java POJO 代码看起来像

public static class SaleLines {

    @JsonProperty("SaleLine")
    private ArrayList<SaleLine> saleLine;

    public ArrayList<SaleLine> getSaleLine() { return saleLine; }

    public void setSaleLine(ArrayList<SaleLine> saleLine) { this.saleLine = saleLine; }
}

public static class SaleLine {
    @JsonProperty("itemID")
    private String itemId;                  //line_item_nk
    @JsonProperty("unitPrice")
    private String unitPrice;
    ....
}

@JsonPropertyOrder({"total", "calcSubTotal", "calcDiscount"})
public static class Sale {

    private String saleTotal, calcSubtotal, calcDiscount; 
    private int salesValueWOVat;

    @JsonProperty("SaleLines")
    SaleLines saleLine;

    @JsonCreator
    public Sale (@JsonProperty("total")String saleTotal,
            @JsonProperty("calcSubtotal")String calcSubtotal,
            @JsonProperty("calcDiscount")String calcDiscount,
            @JsonProperty("SaleLines")SaleLines saleLine,
    ) {
        this.saleTotal = saleTotal;
        this.calcSubtotal = calcSubtotal;
        this.calcDiscount = calcDiscount;
        this.saleLine = saleLine;
        setSalesValueWOVat();
    }

    // getter and setters 

}

@SuppressWarnings({ "rawtypes" })
public static <E, T extends Collection> T readFromJsonAndFillType (
        String json, 
        Modules module,
        Class <T> collectionType,
        Class <E> elementType) 
        throws JsonParseException, JsonMappingException, IOException {

    ObjectMapper objMapper = new ObjectMapper()
        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

    TypeFactory tf = objMapper.getTypeFactory();
    JsonNode node = objMapper.readTree(json).get(module.jsonFieldName); 
    return objMapper.readValue(node.toString(),
            tf.constructCollectionType(collectionType, elementType));

}

主要

ArrayList<Sale> saleList = readFromJsonAndFillType(
                saleJSON, 
                Modules.SALE, 
                ArrayList.class,
                Sale.class);

for (Sale sale: saleList) {
    System.out.println(sale.getSaleLines().getSaleLine().size()); //ERROR Null Pointer Exception
    System.out.println(sale.toString());
}

所以,问题是 SaleLine 没有按预期填充

可能您的JSON无效;例如你问题的最新版本中缺少逗号。

如果问题是您的 JSON 在语法上无效,那么您要么需要在解析 JSON 之前破解它,要么破解解析器以接受无效的 JSON。

另一方面,您的某些 JSON 记录可能缺少 SaleLineSaleLines 属性,或者具有 null 而不是其中一个价值。如果可能的话,添加一些空测试...并拒绝记录或处理丢失的数据。