这是我的Pojo:
public static class MyPojo {
private int rootId;
private String command;
private Double value;
// I want this property to be shown at root level
@JsonIgnore
public int getRootId() {
return rootId;
}
public void setRootId(int rootId) {
this.rootId = rootId;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
}
这是我的第一个序列化方法:
public static void writeJsonId6() throws JsonProcessingException {
MyPojo pojo = new MyPojo();
pojo.setRootId(6);
pojo.setCommand("property.batch");
pojo.setValue(129.00);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
String json = mapper.writer().withRootName(Integer.toString(pojo.getRootId())).writeValueAsString(pojo);
System.out.println(json);
}
Json输出: {“6”:{“command”:“property.batch”,“value”:129.0}}
这是我的第二个序列化方法:
public static void writeJsonId7() throws JsonProcessingException {
MyPojo pojo = new MyPojo();
pojo.setRootId(7);
pojo.setCommand("property.batch");
pojo.setValue(88.00);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
String json = mapper.writer().withRootName(Integer.toString(pojo.getRootId())).writeValueAsString(pojo);
System.out.println(json);
}
Json输出: {“7”:{“command”:“property.batch”,“value”:88.0}}
这就是我需要的:
{“6”:{“command”:“property.batch”,“value”:129.0},“7”:{“command”:“property.batch”,“value”:88.0} }
Jackson lib版本:jackson-core:2.0.0,jackson-databind:2.9.0
答案 0 :(得分:0)
您可以尝试使用Json Streams:
JsonFactory factory = new JsonFactory();
JsonGenerator generator = factory.createGenerator(new PrintWriter(System.out));
generator.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
generator.writeStartObject();
generator.writeObject(firstPojo);
generator.writeObject(secondPojo);
generator.writeEndObject();
答案 1 :(得分:0)
只需创建一个Map<String, MyPojo>
,包含“6”和“7”作为键,并将相应的POJO作为值,并序列化该地图。