简体   繁体   English

使用Jackson解析以数字为键的JSON数组?

[英]Parsing JSON Array with numbers as keys using Jackson?

How to parse following kind of JSON Array using Jackson with preserving order of the content: 如何使用Jackson解析以下种类的JSON数组并保留内容的顺序:

{
  "1": {
    "title": "ABC",
    "category": "Video",
  },
  "2": {
    "title": "DEF",
    "category": "Audio",
  },
  "3": {
    "title": "XYZ",
    "category": "Text",
  }
}

One simple solution: rather than deserializing it directly as an array/list, deserialize it to a SortedMap<Integer, Value> and then just call values() on that to get the values in order. 一个简单的解决方案:与其直接将其反序列化为数组/列表,反而将其反序列化为SortedMap<Integer, Value> ,然后在其上调用values()以按顺序获取值。 A bit messy, since it exposes details of the JSON handling in your model object, but this is the least work to implement. 有点混乱,因为它公开了模型对象中JSON处理的详细信息,但这是最少的实现工作。

@Test
public void deserialize_object_keyed_on_numbers_as_sorted_map() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    SortedMap<Integer, Value> container = mapper
            .reader(new TypeReference<SortedMap<Integer, Value>>() {})
            .with(JsonParser.Feature.ALLOW_SINGLE_QUOTES)
            .with(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES)
            .readValue(
                    "{ 1: { title: 'ABC', category: 'Video' }, 2: { title: 'DEF', category: 'Video' }, 3: { title: 'XYZ', category: 'Video' } }");
    assertThat(container.values(),
            contains(new Value("ABC", "Video"), new Value("DEF", "Video"), new Value("XYZ", "Video")));
}


public static final class Value {
    public final String title;
    public final String category;

    @JsonCreator
    public Value(@JsonProperty("title") String title, @JsonProperty("category") String category) {
        this.title = title;
        this.category = category;
    }
}

But if you want to just have a Collection<Value> in your model, and hide this detail away, you can create a custom deserializer to do that. 但是,如果您只想在模型中包含Collection<Value>并将其隐藏起来,则可以创建一个自定义反序列化器来执行此操作。 Note that you need to implement "contextualisation" for the deserializer: it will need to be aware of what the type of the objects in your collection are. 请注意,您需要为反序列化器实现“上下文化”:它将需要知道集合中对象的类型。 (Although you could hardcode this if you only have one case of it, I guess, but where's the fun in that?) (尽管只有一种情况,您可以对它进行硬编码,但是我觉得这有什么意思呢?)

@Test
public void deserialize_object_keyed_on_numbers_as_ordered_collection() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    CollectionContainer container = mapper
            .reader(CollectionContainer.class)
            .with(JsonParser.Feature.ALLOW_SINGLE_QUOTES)
            .with(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES)
            .readValue(
                    "{ values: { 1: { title: 'ABC', category: 'Video' }, 2: { title: 'DEF', category: 'Video' }, 3: { title: 'XYZ', category: 'Video' } } }");
    assertThat(
            container,
            equalTo(new CollectionContainer(ImmutableList.of(new Value("ABC", "Video"), new Value("DEF", "Video"),
                    new Value("XYZ", "Video")))));
}


public static final class CollectionContainer {
    @JsonDeserialize(using = CustomCollectionDeserializer.class)
    public final Collection<Value> values;

    @JsonCreator
    public CollectionContainer(@JsonProperty("values") Collection<Value> values) {
        this.values = ImmutableList.copyOf(values);
    }
}

(note definitions of hashCode() , equals(x) etc. are all omitted for readability) (请注意,为便于阅读,省略了hashCode()equals(x)等的定义)

And finally here comes the deserializer implementation: 最后是解串器实现:

public static final class CustomCollectionDeserializer extends StdDeserializer<Collection<?>> implements
        ContextualDeserializer {
    private JsonDeserializer<Object> contentDeser;

    public CustomCollectionDeserializer() {
        super(Collection.class);
    }

    public CustomCollectionDeserializer(JavaType collectionType, JsonDeserializer<Object> contentDeser) {
        super(collectionType);
        this.contentDeser = contentDeser;
    }

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property)
            throws JsonMappingException {
        if (!property.getType().isCollectionLikeType()) throw ctxt
                .mappingException("Can only be contextualised for collection-like types (was: "
                        + property.getType() + ")");
        JavaType contentType = property.getType().getContentType();
        return new CustomCollectionDeserializer(property.getType(), ctxt.findContextualValueDeserializer(
                contentType, property));
    }

    @Override
    public Collection<?> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException,
            JsonProcessingException {
        if (contentDeser == null) throw ctxt.mappingException("Need context to produce elements of collection");
        SortedMap<Integer, Object> values = new TreeMap<>();
        for (JsonToken t = p.nextToken(); t != JsonToken.END_OBJECT; t = p.nextToken()) {
            if (t != JsonToken.FIELD_NAME) throw ctxt.wrongTokenException(p, JsonToken.FIELD_NAME,
                    "Expected index field");
            Integer index = Integer.valueOf(p.getText());
            p.nextToken();
            Object value = contentDeser.deserialize(p, ctxt);
            values.put(index, value);
        }
        return values.values();
    }
}

This covers at least this simple case: things like the contents of the collection being polymorphic types may require more handling: see the source of Jackson's own CollectionDeserializer. 至少涵盖了这种简单情况:诸如集合内容为多态类型之类的事情可能需要更多处理:请参阅Jackson自己的CollectionDeserializer的来源。

Also, you could use UntypedObjectDeserializer as a default instead of choking if no context is given. 另外,如果未提供上下文,则可以将UntypedObjectDeserializer用作默认值,而不是阻塞。

Finally, if you want the deserializer to return a List with the indices preserved, you can modify the above and just insert a bit of post-processing of the TreeMap: 最后,如果您希望解串器返回保留索引的List,则可以修改上面的内容,然后插入TreeMap的一些后处理:

        int capacity = values.lastKey() + 1;
        Object[] objects = new Object[capacity];
        values.forEach((key, value) -> objects[key] = value);
        return Arrays.asList(objects);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM