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

时间:2019-04-19 10:15:02

标签: java json

我正在尝试创建一个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" : ""
      }
  }
}

1 个答案:

答案 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”:“”,“姓名”:“”}}}