转换为pojo时,为什么我的属性无法识别

时间:2017-11-02 14:10:51

标签: java json

我有以下JSON:

{ "_id" : "3", "longitude" : "3222", "latitude" : "55", "timeDateOfUsage" : ["02/11/17 13:30:35", "1", "02/11/17 13:30:45", "1", "02/11/17 13:30:51", "0"] }

我正在尝试使用杰克逊将其转换为pojo。这就是我所拥有的:

String inputJson = "{ \"_id\" : \"3\", \"longitude\" : \"3222\", 

\"latitude\" : \"55\", \"timeDateOfUsage\" : [\"02/11/17 13:30:35\", \"1\", \"02/11/17 13:30:45\", \"1\", \"02/11/17 13:30:51\", \"0\"] }";
        ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, JsonAutoDetect.Visibility.ANY);
        mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        try{
            dbResponseonce  response = mapper.readValue(inputJson,dbResponseonce.class);
            System.out.println(response.getLatitude());
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

我的另一个类的字段被命名为JSON中的元素,并具有getter和setter。

上面的代码可以工作,但是当我只创建一个没有配置的基本ObjectMapper对象时,它不起作用。为什么是这样?这是堆栈跟踪错误:

org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "_id" (Class dbResponseonce), not marked as ignorable

这是我的pojo类,它有getter和setter:

public class dbResponseonce {

private String _id;

public String getId() { return this._id; }

public void setId(String _id) { this._id = _id; }

private String longitude;

public String getLongitude() { return this.longitude; }

public void setLongitude(String longitude) { this.longitude = longitude; }

private String latitude;

public String getLatitude() { return this.latitude; }

public void setLatitude(String latitude) { this.latitude = latitude; }

private ArrayList<String> timeDateOfUsage;

public ArrayList<String> getTimeDateOfUsage() { return this.timeDateOfUsage; }

public void setTimeDateOfUsage(ArrayList<String> timeDateOfUsage) { this.timeDateOfUsage = timeDateOfUsage; }}

1 个答案:

答案 0 :(得分:2)

_id的getter和setter不正确。

尝试按如下方式定义它们:

public String get_id() {
    return _id;
}

public void set_id(String _id) {
    this._id = _id;
}

或者使用_id @JsonProperty("_id")

的getter或setter