我正在尝试使用一个属性的属性序列化myrootclass,该属性是第二类myclass的元素集合:

public class MyRootClass {
   private List<MyInterface> list = new ArrayList<MyInterface>();
   // getter / setter
}

public class MyClass implements MyInterface {
   private String value = "test";    
   // getter / setter
}

以下代码:

MyRootClass root = new MyRootClass();
root.getList().add(new MyClass());
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(System.out, root);

生成此JSON输出:

{"list": [ {"value":"test"} ] }

而不是我需要的,收集中的每个对象都用名称序列化:

{"list": [ {"myclass": {"value":"test"}} ] }

有什么方法可以使用杰克逊实现它?我考虑过编写自定义序列化器,但是我没有找到与对象集合有关的任何内容。

有帮助吗?

解决方案

这取决于您想要用名称实现的目标;但是,是的,如果您想包括“ myclass”是类型的信息(或者可以像使用时一样;如果您不使用杰克逊进行杰克逊进行挑选,则可以做到这一点并不重要)。

如果是这样,您将注释myinterface:

@JsonTypeInfo(use=Id.NAME, include=As.WRAPPER_OBJECT)

和myclass与:

@JsonTypeName("myclass")

(如果您不定义该定义,则默认名称将是类无限制的名称)

@JsonTypeInfo 上面定义了要使用该类型名称(而不是Java类名称或自定义方法),并且包含是通过使用包装对象(替代品是包装器数组和Aspoperty)

因此,您应该看到预期的输出。

其他提示

您想要的是在输出中包括类的名称。这不是JSON系列化的行为方式 - 它们仅包含字段名称。

您可以做的是介绍另一堂课。

class MyClass implements MyInterface {
    private MyOtherClass myclass;
}

class MyOtherClass {
    private String value = "test";
}

您可以使用这样的辅助对象:

public static class MyObject {
    public int i;
    public MyObject(int i) { this.i = i; }
    public MyObject() {}
}

@JsonDeserialize(contentAs=MyObject.class)
public static class MyHelperClass extends ArrayList<MyObject> {

}

@Test
public void testCollection() throws JsonGenerationException, JsonMappingException, IOException {
    final Collection<MyObject> l = new ArrayList<MyObject>();
    l.add(new MyObject(1));
    l.add(new MyObject(2));
    l.add(new MyObject(3));

    final ObjectMapper mapper = new ObjectMapper();

    final String s = mapper.writeValueAsString(l);
    final Collection<MyObject> back = mapper.readValue(s, MyHelperClass.class);

}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top