2017-07-01 42 views
2

Java對象我有一個JSON:轉換ObjectNode使用傑克遜

{ 
"response": { 
    "GeoObjectCollection": { 
     "featureMember": [ 
      { 
       "GeoObject": { 
        "description": "Country", 
        "name": "City", 
        "Point": { 
         "pos": "31.992615 45.057626" 
        } 
       } 
      }, 
      { 
       "GeoObject": { 
        "description": "Country", 
        "name": "City", 
        "Point": { 
         "pos": "49.242414 49.895935" 
        } 
       } 
      } 
     ] 
    } 
} 

}

我創建DTO:

GeographicCoordinateDto.java

@Data 
@JsonIgnoreProperties(ignoreUnknown = true) 
public class GeographicCoordinateDto { 
    @JsonProperty("description") 
    private String location; 
    @JsonProperty("name") 
    private String cityName; 
    @JsonProperty("Point") 
    private GeographicCoordinatesDto geoCoordinates; 
} 

GeographicCoordinatesDto.java

@Data 
@JsonIgnoreProperties(ignoreUnknown = true) 
public class GeographicCoordinatesDto { 
    @JsonProperty("pos") 
    private String geoCoordinates; 
} 

然後我得到JsonNode

List<JsonNode> responseArrayOfObjects = mapper.readValue(new URL(yandexGeoCoderRestUrl+address), ObjectNode.class).findValues("GeoObject"); 

而且我想轉換到我的DTO

GeographicCoordinatesDto geo = mapper.convertValue(responseArrayOfObjects.get(0), GeographicCoordinatesDto.class); 

但是,我已經空對象,

GeographicCoordinatesDto(geoCoordinates=null) 

什麼可能是錯的?

UPDATE:

responseArrayOfObjects包含:

enter image description here

+0

我會檢查所有的' JsonNode在列表中。閱讀JSON可能有錯誤? – Chris

回答

2

您正在嘗試從GeographicCoordinatesDto對象獲取pos,但它是GeographicCoordinatesDtoPoint對象內。

你可以這樣做,而不是:

List<JsonNode> responseArrayOfObjects = mapper.readValue(new URL(yandexGeoCoderRestUrl+address), ObjectNode.class).findValues("Point"); 

或創建點的另一個類:

@JsonIgnoreProperties(ignoreUnknown = true) 
class Point { 
    @JsonProperty("pos") 
    private String geoCoordinates; 
} 

GeographicCoordinatesDto使用它:

@JsonIgnoreProperties(ignoreUnknown = true) 
class GeographicCoordinatesDto { 
    @JsonProperty("Point") 
    private Point point; 
} 
+1

我犯了一個錯誤。而是'GeographicCoordinateDto.class',我寫了'GeographicCoordinatesDto.class' –