Jackson ObjectMapper(没有自定义@JsonCreator)是否可以将这个Json解组到提供的Java Dto?

时间:2019-01-17 18:15:34

标签: java json spring spring-boot jackson

我有两个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,我希望能够接受以下内容:

JSON:

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

,然后将其转换为以下实例的等价

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

Jackson / ObjectMapper有可能吗? 我需要什么设置和注释?

1 个答案:

答案 0 :(得分:2)

如果您的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]]]