我正在尝试创建一个 json,其中外部类对象具有所有内部类的字段,但我不希望 json 中包含内部类的对象。
我试过这个:
public class College {
Student student;
class Student {
int id;
String name;
}
}
实际结果:
{
"college" {
"student" {
"id" : "",
"name" : ""
}
}
}
期望:
{
"college" {
"id" : "",
"name" : ""
}
}
最佳答案
嗯,它看起来不像是正确的 json。
如果您使用的是 jackson 库,请使用 @JsonUnwrapped
注释
如果您想要的结果与您预期的类似...如下所示:
大学类(class):
class College {
@JsonUnwrapped
Student student;
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
}
学生类(class):
class Student {
String id;
String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
测试代码:
class JacksonTest {
@Test
public void objToJsonTest() {
Student student = new Student();
College college = new College();
college.setStudent(student);
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
String s = null;
try {
s = mapper.writeValueAsString(college);
} catch (Exception e) {
// handle exception
}
// print json format string
System.out.println(s);
}
}
结果:
{"College":{"id":"","name":""}}
没有@JsonUnwrapped
注解:
{"College":{"student":{"id":"","name":""}}}
关于java - 将java转换为Json时是否可以忽略内部类名和变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55760260/