14

我有 JSON,具有不同级别的字段,因此我想将其转换为具有一级字段的单个 JSON,例如:

{
  "prop1":"value1",
  "prob2":"value2",
  "prop3": {
     "prop4":"value4",
     "prop5":"value5"
  }
  ... many level fields
}  

结果

{
  "prop1":"value1",
  "prop2":"value2",
  "prop4":"value4",
  "prop5":"value5"
  .......
}

我正在使用带注释的杰克逊@JsonProperty("field"),我对一级字段没有问题,但我不知道如何访问字段在 JSON 中的更多内容,对于这个例子是prop4prop5

4

2 回答 2

21

JsonUnwrapped是要使用的注释,它甚至适用于多级嵌套。例如:

@RunWith(JUnit4.class)
public class Sample {

    @Test
    public void testName() throws Exception {
        SampleClass sample = new SampleClass("value1", "value2", new SubClass("value4", "value5", new SubSubClass("value7")));
        new ObjectMapper().writeValue(System.out, sample);
    }

    @JsonAutoDetect(fieldVisibility=Visibility.ANY)
    public static class SampleClass {
        private String prop1;
        private String prop2;
        @JsonUnwrapped
        private SubClass prop3;

        public SampleClass(String prop1, String prop2, SubClass prop3) {
            this.prop1 = prop1;
            this.prop2 = prop2;
            this.prop3 = prop3;
        }
    }
    @JsonAutoDetect(fieldVisibility=Visibility.ANY)
    public static class SubClass {
        private String prop4;
        private String prop5;
        @JsonUnwrapped
        private SubSubClass prop6;
        public SubClass(String prop4, String prop5, SubSubClass prop6) {
            this.prop4 = prop4;
            this.prop5 = prop5;
            this.prop6 = prop6;
        }

    }
    @JsonAutoDetect(fieldVisibility=Visibility.ANY)
    public static class SubSubClass{
        private String prop7;

        public SubSubClass(String prop7) {
            this.prop7 = prop7;
        }
    }
}

会产生

{"prop1":"value1","prop2":"value2","prop4":"value4","prop5":"value5","prop7":"value7"}
于 2013-05-21T14:20:00.093 回答
0

尝试实现 @JsonUnwrapped 注释。更多信息请访问http://jackson.codehaus.org/1.9.9/javadoc/org/codehaus/jackson/annotate/JsonUnwrapped.html

于 2013-05-20T17:16:03.537 回答