解组数组并没有给我任何值

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

当我解组我的JSON时,Warehouses实例是可以的,但是很多仓库实例都在它的列表中。

每个仓库实例都有url字段,但WarehouseField列表有一个空值的实例。

我不确定我错过了什么。

JSON

{
    "warehouses": [
        {
            "warehouse": {
                "PRiyA": "0",
                "WHID": "1 ALABO",
                "PRixA": ""
            },
            "url": "http://ACL-HPDV6:8080/HSyncREST/api/v1/warehouses/PLL/1 ALABO"
        },
        {
            "warehouse": {
                "PRiyA": "0",
                "WHID": "1000 EDWAR",
                "PRixA": ""
            },
            "url": "http://ACL-HPDV6:8080/HSyncREST/api/v1/warehouses/PLL/1000 EDWAR"
        },
    ],
    "url": "http://ACL-HPDV6:8080/HSyncREST/api/v1/warehouses/PLL",
    "status": " "
}

用于解组的代码

public static void main(String[] args) throws Exception {
  Class<?>[] ctx = {Warehouses.class, Warehouse.class, WarehouseField.class};
  JAXBContext jc = JAXBContext.newInstance(ctx);
  Unmarshaller um = jc.createUnmarshaller();
  um.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");
  um.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false);
  Source json = new StreamSource(new File("D:/warehouses.json"));
  Warehouses warehouses = um.unmarshal(json, Warehouses.class).getValue();

模型类

public class Warehouses {
    public List<Warehouse> warehouses;
    public String url;
    public String status;
    <getters and setters>
}

public class Warehouse {
    public List<WarehouseField> warehouse;
    public String url;
    <getters and setters>
}

public class WarehouseField {
    @XmlAttribute
    public String implName;
    @XmlValue
    public String value;
    <getters and setters>
}
java json jaxb unmarshalling moxy
1个回答
1
投票

首先,我建议您将所有字段设为私有,您的字段中包含getter和setter。

将响应(?)DTO类名称与字段和实际类型命名分开也是一个好主意。

假设响应DTO中的字段名称告诉实际类型,然后像WarehousesWarehousesResponseWarehouseWarehouseResponse进行一些重构。

然后关于“数组”,来自JSON的剪辑:

"warehouse": {
    "PRiyA": "0",
    "WHID": "1 ALABO",
    "PRixA": ""
}

这不是一个名为仓库的数组,因此它不会很好地反序列化为List

它是Warehouse类型的对象(这就是为什么区分WarehouseResponse,为了清楚起见,但也参见后面提到的Map),这是一个名为WarehouseResponse类型的对象仓库的字段(假设您同意命名策略)。

一种选择是创建一个类,如:

@Getter @Setter
public class Warehouse {
    private String PRiyA;
    private String WHID;
    private String PRixA;
}

并更改WarehouseResponse,如:

@Getter @Setter
public class WarehouseResponse {
// Change the list to warehouse object as it is in response
//      private List<WarehouseField> warehouse; 
    private Warehouse warehouse;
    private String url;
    private Date date = new Date();

}

通常,也可以简单地将键/值对(例如)设置为Map<String,String>,因此在这种情况下,WarehouseResponses也可能具有private HashMap<String, String> warehouse,并且不需要类Warehouse。但是我无法使用我的Moxy知识。

所以我介绍了如何反序列化(和序列化)您在JSON中提供的格式,但我不知道这适合您可能的XML需求

热门问题
推荐问题
最新问题