2016-08-06 47 views
0

这个问题是重复的Link,代码被用作:杰克逊:商店嵌套的JSON对象的JSONObject

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。

+0

尝试使用注释'@ JsonAnySetter'和'@ JsonAnyGetter'注解[这里](http://www.programcreek.com/java-api-examples/index.php?api=com.fasterxml.jackson.annotation.JsonAnySetter)一个如何使用它的例子。 –

+0

@MarioAlexandroSantini我试过** Example1 **从你提供的链接。但它也设置了其他不在POJO'Car'中的字段。我只是想要在“设置”键(它是'JSONObject')下的对象 –

回答

0

首先,你的意思是的JSONObject是标准从Java EE 7,而不是的JSONObject这是在Android中。

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

比,这里是我的车例如:

包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的值 性质