当我解组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>
}

最佳答案

首先,我建议您将所有字段都设为私有,您的字段应具有getter和setter方法。

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

假定响应DTO中的字段名称指示实际类型,然后进行一些重构,例如WarehousesWarehousesResponseWarehouseWarehouseResponse

然后关于“数组”,从JSON剪辑:

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


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

它是类型为Warehouse的对象(这就是为什么要区分WarehouseResponse,为清楚起见,另请参见后述Map),它是类型为WarehouseResponse的对象中的名为Warehouse的字段(假设您同意命名策略)。

一种选择是创建一个类似的类:

@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>,因此在这种情况下,WarehouseResponse也可以具有private HashMap<String, String> warehouse,并且不需要类Warehouse。但是,我无法使用Moxy知识进行操作。

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

10-07 23:04