在Java中使用杰克逊注释反序列化字符串和对象

时间:2019-05-10 20:08:40

标签: java json jackson

我当前的json文件如下:

{
  "root": {
    "node1a":[
    ],
    "node1b":[
      "foo",
      "bar"
    ]
  }
}

和杰克逊反序列化:

@JsonCreator
class DeserializationClass{

    Map<String, List<String>> nodes;

    DeserializationClass(@JsonProperty("root") final Map<String, List<String>> nodes) {
        this.nodes = nodes;
    }
}

但是,我想转到

这样的结构
{
  "root": {
    "node1a":[
    ],
    "node1b":[
      "foo",
      "bar",
      {
        "key1":"value",
        "key2":"value"
      }
    ]
  }
}

是否可以通过替换使用注释对序列号进行反序列化

Map<String, List<String>> 

Map<String, List<AnotherClass>>?

2 个答案:

答案 0 :(得分:0)

您的node1b现在是对象的混合数组,因此,除非您要实现完整的自定义解串器,否则最好的方法是List<Object>,其中某些对象将是{{ 1}} s。

答案 1 :(得分:0)

您可以对POJO项目使用JsonCreator批注和两个构造函数。如果数组1-arg中有一个原语,将使用构造函数。对于完全设置的对象2-arg,将使用构造函数。看下面的例子:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.util.List;
import java.util.Map;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.readValue(jsonFile, DeserializationClass.class));
    }
}


class DeserializationClass {

    Map<String, List<AnotherClass>> nodes;

    @JsonCreator
    DeserializationClass(@JsonProperty("root") final Map<String, List<AnotherClass>> nodes) {
        this.nodes = nodes;
    }

    @Override
    public String toString() {
        return "DeserializationClass{" +
                "nodes=" + nodes +
                '}';
    }
}

class AnotherClass {

    private String key1;
    private String key2;

    @JsonCreator(mode = JsonCreator.Mode.DELEGATING)
    public AnotherClass(@JsonProperty("key1") String value) {
        this(value, null);
    }

    @JsonCreator
    public AnotherClass(@JsonProperty("key1") String key1, @JsonProperty("key2") String key2) {
        this.key1 = key1;
        this.key2 = key2;
    }

    @Override
    public String toString() {
        return "AnotherClass{" +
                "key1='" + key1 + '\'' +
                ", key2='" + key2 + '\'' +
                '}';
    }
}

您的JSON有效负载打印内容:

DeserializationClass{nodes={node1a=[], node1b=[AnotherClass{key1='foo', key2='null'}, AnotherClass{key1='bar', key2='null'}, AnotherClass{key1='value1', key2='value1'}]}}