如何基于json属性前缀在jackson中创建数组字段?

时间:2016-12-06 19:58:48

标签: java json jackson

说我有以下json字符串:

{
    "name": "Foo"
    "pic1": "some pic 1",
    "pic2": "some pic 2",
    "pic3": "some pic 3",
    ...
    "picn": "some pic n"
}

我需要创建以下POJO:

class Foo {
  String name;
  String[] pics;
}

来自这个字符串。

诀窍是我需要以某种方式将pic *映射到String [] pics。

我怎么能用杰克逊做到这一点?

1 个答案:

答案 0 :(得分:1)

添加您自己的自定义序列化程序和反序列化程序。

@JsonSerialize(using = MySerializer.class)
@JsonDeserialize(using = MyDeSerializer.class)
public class Foo {
    private String name;
    private String[] pics;

串行:

public class MySerializer extends JsonSerializer<Foo> {

    @Override
    public void serialize(Foo value, JsonGenerator jgen, SerializerProvider serializers) throws IOException {
        int i = 1;
        String fieldName = "pics";
        jgen.writeStartObject();
        jgen.writeStringField("name", value.getName());
        for (String stringValue : value.getPics()) {
            jgen.writeStringField(fieldName + i, stringValue);
            i++;
        }
        jgen.writeEndObject();

    }

}

解串器:

public class MyDeSerializer extends JsonDeserializer<Foo> {

    @Override
    public Foo deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
        ObjectCodec objectCodec = jp.getCodec();
        Foo foo = new Foo();
        JsonNode node = objectCodec.readTree(jp);

        Iterator<Entry<String, JsonNode>> fields = node.fields();
        String[] pics = new String[node.size() - 1];

        int i = 0;
        while (fields.hasNext()) {
            Entry<String, JsonNode> next = fields.next();
            if (next.getKey().equalsIgnoreCase("name"))
                foo.setName(node.get("name").asText());
            else {
                pics[i] = node.get(next.getKey()).asText();
                i++;
            }
        }
        foo.setPics(pics);
        return foo;
    }
}