0

此问题与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。

4

1 回答 1

0

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

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

比,这是我的汽车示例:

包 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

所以它只适用于 Jackson Annotation doc中描述的设置

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

于 2016-08-06T15:13:15.103 回答