且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Jackson将JSON数组中的子文档表示为Java Collection?

更新时间:2023-01-17 11:17:04

如果JSON输入的结构是完全动态的,则可以将其读取为JsonNode甚至是Map.有关更多信息,请参考此链接.

If the structure of your JSON input is completely dynamic, you can read it as JsonNode or even as Map. Refer to this link for more info.

如果您想将JSON映射到Java类,但您不知道编译类型中的所有属性,则可以利用

If you want to map your JSON to java classes but you don't know all the attributes in compile type, you can leverage the @JsonAnyGetter/@JsonAnySetter annotations. Here is an example based on your JSON that stores the unknown attributes for the Address class in the internal map.

public class JacksonMapping {
    public static final String JSON = "...";

    public static class Attributes {
        public String type;
        public URI url;
    }

    public static class Address {
        public String city;
        public String country;
        public String state;
        public Integer stateCode;
        public String street;
        private final Map<String, Object> otherAttributes = new HashMap<>();

        @JsonAnySetter
        public void setProperty(String name, Object value) {
            otherAttributes.put(name, value);
        }

        @JsonAnyGetter
        public Map<String, Object> getOtherAttributes() {
            return otherAttributes;
        }
    }

    public static class Record {
        @JsonProperty("Id")
        public String id;
        @JsonProperty("Name")
        public String name;
        public Attributes attributes;
        @JsonProperty("Address")
        public Address address;
        @JsonProperty("Phone")
        public String phone;
    }

    public static class RecordList {
        public List<Record> records;
    }

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        RecordList recordList = mapper.readValue(JSON, RecordList.class);
        System.out.println(mapper.writerWithDefaultPrettyPrinter()
                .writeValueAsString(recordList));
    }

}

在工具的帮助下,我也可以尝试从JSON生成Java对象.例如以下示例: http://www.jsonschema2pojo.org

I can also try to generate java objects from your JSON with a help from a tool. For example this one: http://www.jsonschema2pojo.org