@JsonProperty Json对象里面的Json对象

时间:2013-07-01 02:29:48

标签: java json jackson

如何使用@JsonProperty()在另一个json对象中获取json对象?我想得到的例子是json:

"location" : {
  "needs_recoding" : false,
  "longitude" : "-94.35281245682333",
  "latitude" : "35.35363522126198",
  "human_address" : "{\"address\":\"7301 ROGERS AVE\",\"city\":\"FORT SMITH\",\"state\":\"AR\",\"zip\":\"\"}"
}

1 个答案:

答案 0 :(得分:2)

在构造函数中使用A helpful reference注释的

@JsonPropertyStaxMan提供。一个简单的例子如下所示:

public class Address {
    private String address;
    private String city;
    private String state;
    private String zip;

    // Constructors, getters/setters
}

public class Location {
    private boolean needsRecoding;
    private Double longitude;
    private Double latitude;
    private Address humanAddress;

    public Location() {
        super();
    }

    @JsonCreator
    public Location(
        @JsonProperty("needs_recoding") boolean needsRecoding,
        @JsonProperty("longitude") Double longitude,
        @JsonProperty("latitude") Double latitude,
        @JsonProperty("human_address") Address humanAddress) {

        super();
        this.needsRecoding = needsRecoding;
        this.longitude = longitude;
        this.latitude = latitude;
        this.humanAddress = humanAddress;
    }

    // getters/setters
}

或者,您可以将内容直接反序列化为JSON对象树。下面对Location类示例稍作修改进行了说明:

public class Location {
    private boolean needsRecoding;
    private Double longitude;
    private Double latitude;

    // Note the use of JsonNode, as opposed to an explicitly created POJO
    private JsonNode humanAddress;

    public Location() {
        super();
    }

    @JsonCreator
    public Location(
        @JsonProperty("needs_recoding") boolean needsRecoding,
        @JsonProperty("longitude") Double longitude,
        @JsonProperty("latitude") Double latitude,
        @JsonProperty("human_address") JsonNode humanAddress) {

        super();
        this.needsRecoding = needsRecoding;
        this.longitude = longitude;
        this.latitude = latitude;
        this.humanAddress = humanAddress;
    }

    // getters/setters
}
相关问题