我使用JAXB注释来使用Spring序列化/反序列化对象。
这是我的回复课程:
@XmlRootElement(name = "animals")
public class PetClinic implements Serializable {
@XmlElementWrapper(name = "animals")
@XmlElement(name = "animal")
private Collection<Animal> animals;
public Collection<Animal> getAnimals() {
return animals;
}
public void setAnimalsCollection<Animal> animals) {
this.animals = animals;
}
}
我想获得像这样的JSON
{
"animals": [
{...},
{...}
]
}
我试图解开根元素,但我的所有解决方案都不起作用:
1)我试图在字段
上使用@JsonUnwrapped注释2)我尝试使用@JsonSerialize
@JsonSerialize(using = PetClinicSerializer.class)
串行器代码:
ObjectMapper mapper = new ObjectMapper();
@Override
public void serialize(PetClinic clinic, JsonGenerator generator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
String clinicAsString = mapper.writeValueAsString(clinic);
generator.writeString(clinicAsString);
}
如何获得上述JSON?
答案 0 :(得分:1)
我刚刚使用ObjectMapper
而没有任何jaxb表示法并获得了所需的结果:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
public class PetClinic implements Serializable {
private Collection<Animal> animals;
public Collection<Animal> getAnimals() {
return animals;
}
public void setAnimals(Collection<Animal> animals) {
this.animals = animals;
}
public static void main(String[] args) throws Exception {
PetClinic pc = new PetClinic();
Animal cat = new Animal();
cat.setName("cat");
Animal dog = new Animal();
dog.setName("dog");
pc.setAnimals(Arrays.asList(cat, dog));
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
String s = mapper.writeValueAsString(pc);
System.out.println(s);
}
}
class Animal {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
输出
{
"animals" : [ {
"name" : "cat"
}, {
"name" : "dog"
} ]
}