我正在使用 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();
}
实现类:
@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 序列化:
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);
}
}
Test:
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.
我已尝试了所有能找到的建议解决方案,但未能实现我的目标。我看过:
- Jackson:自定义集合序列化为 JSON https://stackoverflow.com/questions/3954265/jackson-custom-collection-serialization-to-json
- 如何使用 Java Jackson 重命名 JSON 的根键? https://stackoverflow.com/questions/8034933/how-do-i-rename-the-root-key-of-a-json-with-java-jackson
- Jackson:自定义集合序列化为 JSON https://stackoverflow.com/questions/3954265/jackson-custom-collection-serialization-to-json
或者我错过了什么?我为此使用 jackson 1.9.12。欢迎在这方面提供任何帮助。