有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我试图创建一个json,其中外部类对象具有所有内部类的字段,但我不希望json中包含内部类的对象

我试过这个:

public class College {
    Student student;

    class Student {
        int id;
        String name;
    }
}

实际结果:

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

期望:

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

共 (1) 个答案

  1. # 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);
        }
    }
    


    结果:

    {"College":{"id":"","name":""}}

    没有@JsonUnwrapped注释:

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