有没有办法使用 Jackson ObjectMapper(没有自定义@JsonCreator)将此 Json 解组到提供



我有两个Java类:

public class Request
{
    private List<Item> subItems;
    public Request()
    {
    }
    public List<Item> getSubItems()
    {
        return subItems;
    }
    public void setSubItems(List<Item> subItems)
    {
        this.subItems = subItems;
    }
}
class Item
{
    private String name;
    private String functionName;
    //...elided...
}

将传递的subItems可以是复杂的(包括函数)或简单的(只是一个名称)。可以混合使用这两种情况。为了简化 JSON,我希望能够接受以下内容:

杰森:

{
  "subItems": [
    {
      "name": "complexType",
      "function": "someFunction"
    },
    "simpleType"
  ]
}

然后将其转换为以下实例的等效项:

Request request = new Request();
request.setSubItems(
    Arrays.asList(
        new Item( "complexType", "SomeFunction" ),
        new Item( "simpleType" )
    )
);

这在Jackson/ObjectMapper上可能吗?我需要哪些设置和注释?

如果你的Item类有一个字符串构造函数,它将使用 "simpleType" 值调用。

class Item {
    private String name;
    private String functionName;
    public Item() {
    }
    public Item(String name) {
        this.name = name;
    }
    // getters and setters here
}

完整演示

public class Request {
    public static void main(String[] args) throws IOException {
        String json = "{"subItems":[" +
                          "{"name":"complexType","functionName":"SomeFunction"}," +
                          ""simpleType"" +
                      "]}";
        Request request = new ObjectMapper().readValue(json, Request.class);
        System.out.println(request);
    }
    private List<Item> subItems;
    public Request() {
    }
    public Request(Item... subItems) {
        this.subItems = Arrays.asList(subItems);
    }
    public List<Item> getSubItems() {
        return this.subItems;
    }
    public void setSubItems(List<Item> subItems) {
        this.subItems = subItems;
    }
    @Override
    public String toString() {
        return "Request [subItems=" + this.subItems + "]";
    }
}
class Item {
    private String name;
    private String functionName;
    public Item() {
    }
    public Item(String name) {
        this.name = name;
    }
    public Item(String name, String functionName) {
        this.name = name;
        this.functionName = functionName;
    }
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getFunctionName() {
        return this.functionName;
    }
    public void setFunctionName(String functionName) {
        this.functionName = functionName;
    }
    @Override
    public String toString() {
        return "Item [name=" + this.name + ", functionName=" + this.functionName + "]";
    }
}

输出

Request [subItems=[Item [name=complexType, functionName=SomeFunction], Item [name=simpleType, functionName=null]]]

相关内容

  • 没有找到相关文章

最新更新