如何使用@JsonProperty注释访问JSON子字段?

时间:2013-05-22 17:04:40

标签: java json jackson

我需要在另一个不同的json中转换json,我使用@JsonProperty注释来更改名称字段JSON结果,但我不知道访问字段封装在不同的json级别,例如:

{  "prop1" : "value1",
   "prop2" : "value2",
   "prop3" : {
     "prop4" : "value4",
     "prop5" : {
        "prop6" : "value6"
     } 
  }
}

json结果

  { 
    "prop1_new_name":"value1",
    "prop4_new_name":"value4",
    "prop6_new_name":"value6"  
  }

2 个答案:

答案 0 :(得分:1)

这似乎是您之前question的延续。因此,除了在答案中解释使用@JsonUnwrapped之外,还需要在声明它的类中的字段上添加@JsonProperty。使用@JsonProperty修改上一个答案可以为您提供:

@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 {
        @JsonProperty("prop4_new_name")
        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{
        @JsonProperty("prop7_new_name")
        private String prop7;

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

结果这样:

{"prop2":"value2","prop5":"value5","prop7_new_name":"value7","prop4_new_name":"value4","prop1_new_name":"value1"}

答案 1 :(得分:0)

反序列化时,

“prop3”将是Java对象中的Map(如果已正确注释)。然后,您可以创建自定义JsonSerializer以输出预期结果。

要创建自定义JsonSerializer,您可以按照以下指南操作:http://dev.sghill.net/2012/04/how-do-i-write-jackson-json-serializer.html