Jackson:将嵌套的json对象存储为JSONObject

时间:2016-08-06 09:00:04

标签: java jackson jsonobject objectmapper jackson-databind

此问题与Link重复,代码用作:

ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
Car car = mapper.readValue(new File("fileName"), Car.class);

但是对于链接中给出的settings,值为{}。如何解决这个问题?我想使用嵌套对象作为JSONObject。

1 个答案:

答案 0 :(得分:0)

首先,您指的是来自Java EE 7的标准的 JsonObject ,而不是Android中的 JSONObject

即使在您提供的链接中,他们也会谈论它。

比,这是我的汽车示例:

package org.mas.examples.jackson.models;

import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

import javax.json.JsonObject;

public class Car {

    @JsonProperty(value="id")
    private long id;

    @JsonProperty(value="name")
    private String name;

    @JsonIgnore
    private JsonObject settings;

    public void setId(long id) {
        this.id = id;
    }

    public long getId() {
        return this.id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    public void setSettings(JsonObject settings) {
        this.settings = settings;
    }

    public JsonObject getSettings() {
        return settings;
    }

    @JsonAnySetter
    public void setJsonProperty(String key, Object value) {

        if ("settings".equals(key)) {

            System.out.println("Got it " + key + " value: " + value);

            /* JsonObject settings = ....;  create here your JsonObject */

        } else {
            System.out.println(key + " value: " + value);
        }

    }
}

如果你运行这样的测试:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

try {
    Car car = objectMapper.readValue(json, Car.class);

    System.out.println("Load a car: " + car.getName());

} catch (IOException e) {
    e.printStackTrace();
}

您将获得以下结果:

Got it settings value: {color=#ff0000}
Load a car: test

所以它只适用于杰克逊注释doc中所述的设置

  

@JsonAnySetter:用于将双参数方法定义为的注释   “任何setter”,用于反序列化未映射的JSON的值   特性