我正在尝试创建一个json,其中外部类对象具有所有内部类的字段,但我不希望json中具有内部类的对象。
我尝试过:
[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in /var/jenkins_home/jobs/pipe/jobs/pd.oh52a1/branches/dev/workspace
[Pipeline] {
[Pipeline] sh
+ echo /var/jenkins_home/jobs/pipe/jobs/pd.oh52a1/branches/dev/workspace
[Pipeline] }
[Pipeline] // node
[Pipeline] echo
实际结果:
public class College {
Student student;
class Student {
int id;
String name;
}
}
期望:
{
"college" {
"student" {
"id" : "",
"name" : ""
}
}
}
答案 0 :(得分:1)
好吧,它看起来不像是正确的json。
如果您使用的是jackson库,请使用@JsonUnwrapped
批注
如果您想要的结果与您期望的...类似,如下所示:
class College {
@JsonUnwrapped
Student student;
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
}
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);
}
}
{“学院”:{“ id”:“”,“名称”:“”}}
@JsonUnwrapped
批注:{“大学”:{“学生”:{“ id”:“”,“姓名”:“”}}}