我的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没有按预期填充
答案 0 :(得分:1)
您的JSON可能无效;例如您的问题中的最新版本中缺少逗号。
如果问题是您的JSON在语法上无效,那么您需要在解析JSON之前破解JSON或者破解解析器以接受无效的JSON。
另一方面,您的某些JSON记录可能缺少SaleLine
或SaleLines
属性,或者有null
而不是其中一个值。如果可能,请添加一些空测试...并拒绝记录或处理丢失的数据。