用Jackson解析非均匀JSON对象数组 [英] Parsing an array of non-homogeneous JSON Objects with Jackson

查看:147
本文介绍了用Jackson解析非均匀JSON对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一种情况,我需要解析一个不相同的JSON对象数组.

I have a situation where I need to parse an array of JSON objects that are not identical.

例如:

[ 
 { "type": "type1", ..... type1 contents .... }, 
 { "type": "type2", ..... type2 contents .... },
 ....
 { "type": "type1", ..... type1 contents .... }
]

类型的数量是有限的,每种类型的内容都可以定义,但是无法定义将容纳内容的对象的单一类型.

The number of types is limited and the contents of each type are well can be defined but it is not possible to define a single type of object that will hold the contents.

有没有办法和杰克逊一起解析它们?

Is there a way to parse them with Jackson?

P.S.如果可以的话,我会尽量避免编写自定义解析器.

P.S. I am trying to avoid writing a custom parser if I can help it.

推荐答案

我会使用

com.fasterxml.jackson.databind.JsonNode.

JsonNode parsed = objectMapper
                   .readValue("[{\"name\": \"a\"},{\"type\":\"b\"}]", JsonNode.class);

此类有大量的实用方法可以使用.

This class has tons of utility methods to work with.

或者特定于数组,您可以使用:

Or specific for arrays you can use:

com.fasterxml.jackson.databind.node.ArrayNode

ArrayNode value = objectMapper
                   .readValue("[{\"name\": \"a\"},{\"type\":\"b\"}]", ArrayNode.class);

编辑

对不起,我误解了您的问题,您可以使用@JsonTypeInfo进行多态序列化/反序列化:

Sorry, I have misread your question, you can use @JsonTypeInfo for polymorphic serialization/deserialization:

public static void main(String args[]) throws JsonProcessingException {

    //language=JSON
    String data = "[{\"type\":\"type1\", \"type1Specific\":\"this is type1\"},{\"type\":\"type2\", \"type2Specific\":\"this is type2\"}]";
    ObjectMapper objectMapper = new ObjectMapper();

    List<BaseType> parsed = objectMapper.readValue(data, new TypeReference<List<BaseType>>() {});
    System.out.println(parsed);
}


@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", include = JsonTypeInfo.As.PROPERTY)
@JsonSubTypes(value = {
        @JsonSubTypes.Type(value = Type1.class, name = "type1"),
        @JsonSubTypes.Type(value = Type2.class, name = "type2")
})
static public abstract class BaseType {
    public String type;
}
static public class Type1 extends BaseType {
    public String type1Specific;
    @Override
    public String toString() {
        return "Type1{" +
                "type1Specific='" + type1Specific + '\'' +
                '}';
    }
}
static public class Type2 extends BaseType {
    public String type2Specific;

    @Override
    public String toString() {
        return "Type2{" +
                "type2Specific='" + type2Specific + '\'' +
                '}';
    }
}

以下是文档:

https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization

希望这会有所帮助.

结果将是:

[Type1{type1Specific='this is type1'}, Type2{type2Specific='this is type2'}]

这篇关于用Jackson解析非均匀JSON对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆