使用Jackson解析带有数字作为键的JSON数组?

时间:2015-10-24 09:26:35

标签: java android json parsing jackson

如何使用Jackson解析以下类型的JSON数组并保留内容的顺序:

@echo off
chcp 65001
mode con: cols=50 lines=25
setlocal EnableDelayedExpansion
echo. > test.txt
set array[1]=2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2
set array[2]=2 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 2
set array[3]=2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2
for %%b in (1, 2, 3) do (
    for %%i in (!array[%%b]!) do (
        echo Loop Begins
        set LNr=%%i
        echo Loop%LNr%
        goto Loop%LNr%
        :Loop0
        echo 0
        echo|set /p ="░" >> test.txt
        goto LoopE
        :Loop1
        echo 1
        echo|set /p ="█" >> test.txt
        goto LoopE
        :Loop2
        echo 2
        echo|set /p = "#" >> test.txt
        goto LoopE
        :LoopE
    )
    echo. >> test.txt
)
echo. >> test.txt

1 个答案:

答案 0 :(得分:3)

一个简单的解决方案:不是直接将其反序列化为数组/列表,而是将其反序列化为SortedMap<Integer, Value>,然后在其上调用values()以按顺序获取值。有点混乱,因为它暴露了模型对象中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;
    }
}

但是如果你想在你的模型中只有Collection<Value>并隐藏这个细节,你可以创建一个自定义反序列化器来做到这一点。请注意,您需要为反序列化器实现“上下文化”:它需要知道集合中对象的类型。 (虽然你可以硬编码,如果你只有一个案例,我猜,但那里的乐趣在哪里?)

@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);
    }
}

(注意hashCode()equals(x)等的定义均为可读性而省略。

最后是解串器实现:

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();
    }
}

这至少涵盖了这个简单的案例:像多态类型的集合内容这样的东西可能需要更多处理:查看Jackson自己的CollectionDeserializer的来源。

此外,如果没有给出上下文,您可以使用UntypedObjectDeserializer作为默认值而不是choking。

最后,如果您希望反序列化器返回保留索引的List,您可以修改上面的内容并插入一些TreeMap的后处理:

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