将集合反序列化为外部数组

时间:2014-03-14 19:59:25

标签: java collections jackson deserialization

我想将以下类序列化为包含属性numcollection中的项目的数组。

public class Foo {
  private final int num;
  private final Collection<String> collection;
  ...
}

我想:

[num, "a", "b", "c"]

我可以通过用@JsonFormat(shape = JsonFormat.Shape.ARRAY)注释Foo来获取部分路径,但这只能让我:

[num, ["a", "b", "b"]]

我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

您必须为POJO课程编写自定义序列化程序和反序列化程序 串行器:

class FooJsonSerializer extends JsonSerializer<Foo> {

    @Override
    public void serialize(Foo value, JsonGenerator generator, SerializerProvider provider)
            throws IOException, JsonProcessingException {
        generator.writeStartArray();
        generator.writeNumber(value.getNum());
        if (value.getCollection() != null) {
            for (String item : value.getCollection()) {
                generator.writeString(item);
            }
        }
        generator.writeEndArray();
    }
}

解串器:

class FooJsonDeserializer extends JsonDeserializer<Foo> {
    @Override
    public Foo deserialize(JsonParser parser, DeserializationContext context) throws IOException,
            JsonProcessingException {
        String[] array = parser.readValueAs(String[].class);
        int num = 0;
        Collection<String> collection = new ArrayList<String>();
        if (array.length > 0) {
            num = Integer.valueOf(array[0]);
            for (int index = 1; index < array.length; index++) {
                collection.add(array[index]);
            }
        }

        Foo foo = new Foo(num, collection);
        return foo;
    }
}

现在,您必须链接您的POJO类和自定义序列化器/反序列化器实现:

@JsonSerialize(using = FooJsonSerializer.class)
@JsonDeserialize(using = FooJsonDeserializer.class)
class Foo {
}

简单用法:

Foo foo = new Foo(11, Arrays.asList("a", "b", "c"));
ObjectMapper mapper = new ObjectMapper();

String json = mapper.writeValueAsString(foo);
System.out.println("Serialize to JSON:");
System.out.println(json);
System.out.println("Deserialize to POJO:");
System.out.println(mapper.readValue(json, Foo.class));

以上程序打印:

Serialize to JSON:
[11,"a","b","c"]
Deserialize to POJO:
Foo [num=11, collection=[a, b, c]]

答案 1 :(得分:0)

有效的JSON序列化是您获得的序列化,因为生成的字符串可以反序列化为原始对象。

对于您所追求的输出,您可能需要手动完成。