是否可以在将 java 转换为 JSON 时忽略内部类名和变量



>我正在尝试创建一个 json,其中外部类对象具有所有内部类的字段,但我不希望内部类的对象在 json 中。

我试过这个:

public class College {
    Student student;
    class Student {
        int id;
        String name;
    }
}

实际结果:

{
  "college" {
      "student" {
          "id" : "",
          "name" : ""
      }
  }
}

期望:

{
  "college" {
      "id" : "",
      "name" : ""
  }
}

好吧,它看起来不像正确的 json。如果您使用的是杰克逊库,请使用@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":","名称":"}}}

最新更新