java - @JsonProperty Json对象里面的Json对象

标签 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\":\"\"}"
}

最佳答案

A helpful reference使用 @JsonProperty构造函数中的注释由 StaxMan 提供.一个简单的例子如下所示:

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
}

关于java - @JsonProperty Json对象里面的Json对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17396703/

相关文章:

java - 泛型不从 "this"自动推断类型?

java - 如何在 Jackson 中以增量方式从文件中读取 json 序列?

java - 非法 block 大小异常 : Input length must be multiple of 8 when decrypting with padded cipher

java - 我无法让我的 PostFix Evaluator 正常工作

javascript - codeigniter通过ajax和json从数据库获取数据

java - org.json.JSONException : End of input at character 0 of

java - 使用 Jackson 将可变(原始/对象)JSON 属性反序列化为对象

java - 为什么这里不允许转换为 "GenericType<?>"?

java - 用于所有嵌入式带注释对象的单个自定义序列化程序,用它们的 id 替换它们

javascript - JSON.stringify 或如何将二进制数据序列化为 base64 编码的 JSON?