如何使用Jackson序列化嵌套的对象集合

时间:2018-03-23 14:49:55

标签: java java-8 jackson jackson2

拥有以下代码:

public class ToSerialize {
  List<NestedObject> objs;

  public ToSerialize(List<NestedObject> objs) {
    this.objs = objs;
  }
}

public class NestedObject {
  int intValue = 0;
  String strValue = "Hello world";
}

如果可能的话,我如何设置Jackson,以便将以下CSV作为字符串输出:

obj1.intValue,obj1.strValue,obj2.intValue,obj2.strValue,0,"Hello world",0,"Hello world"

我考虑编写自己的自定义JsonSerializer,但无法弄明白。不过,这是我目前没有工作的序列化器实现

  @Override
  public void serialize(List<NestedObject> values, JsonGenerator gen, SerializerProvider serializers)
    throws IOException
  {
    int i = 1;
    for (Iterator<VsppAssetEntry> iterator = values.iterator(); iterator.hasNext(); ) {
      VsppAssetEntry entry = iterator.next();
      String fieldName = "obj" + i;
      gen.writeObjectField(fieldName, entry);
      i++;
    }

这显然是在抛出com.fasterxml.jackson.core.JsonGenerationException: Can not write a field name, expecting a value因为杰克逊在输入此方法之前写了一个fieldName objs

1 个答案:

答案 0 :(得分:0)

我建议Jackson dataformat CSV

请考虑以下CSV架构:

CsvSchema schema = CsvSchema.builder()
        .addColumn("obj")
        .addColumn("intValue")
        .addColumn("strValue")
        .build()
        .withHeader();

ToSerialize toSerialize = new ToSerialize(Arrays.asList(new NestedObject(), new NestedObject()));

String csv = new CsvMapper()
        .writerFor(ToSerialize.class)
        .with(schema)
        .writeValueAsString(toSerialize);

System.out.println(csv);

以及以下自定义序列化程序......

public class ToSerializeSerializer extends JsonSerializer<ToSerialize> {
    @Override
    public void serialize(ToSerialize toSerialize, JsonGenerator gen, SerializerProvider serializers)
            throws IOException {
        List<NestedObject> objs = toSerialize.getObjs();
        for (int i = 0; i < objs.size(); i++) {
            gen.writeObject("obj" + i);
            gen.writeObject(objs.get(i));
        }
    }
}

...在您的ToSerialize课程上注册...

@JsonSerialize(using = ToSerializeSerializer.class)
public class ToSerialize {
    […]
}

......它会给你......

obj,intValue,strValue
obj0,0,"Hello world"
obj1,0,"Hello world"