我使用Jackson对对象列表进行JSON序列化.
以下是我得到的:
{"ArrayList":[{"id":1,"name":"test name"}]}
但我想要这个:
{"rootname":[{"id":1,"name":"test name"}]} // ie showing the string I want as the root name.
以下是我对此的看法:
接口:
public interface MyInterface {
public long getId();
public String getName();
}
Implementation class:
@JsonRootName(value = "rootname")
public class MyImpl implements MyInterface {
private final long id;
private String name;
public MyImpl(final long id,final name) {
this.id = id;
this.name = name;
}
// getters
}
JSon serialization:
public class MySerializer {
public static String serializeList(final List<MyInterface> lists) {
//check for null value.Throw Exception
final ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);
return mapper.writeValueAsString(lists);
}
}
测试:
final List<MyInterface> list = new ArrayList<MyImpl>();
MyImpl item = new MyImpl(1L,"test name");
list.add(item);
final String json = MySerializer.serializeList(list);
System.out.println(json);
以下是我得到的:
{"ArrayList":[{"id":1,"name":"test name"}]}
但我想要这个:
{"rootname":[{"id":1,"name":"test name"}]} // ie showing the string I want as the root name.
我try 了所有我能找到的建议解决方案,但未能实现我的目标.我看过:
- Jackson : custom collection serialization to JSON
- How do I rename the root key of a JSON with Java Jackson?
- Jackson : custom collection serialization to JSON
还是我错过了什么?为此,我使用的是Jackson 1.9.12.欢迎在这方面提供任何帮助.