2016-07-26 67 views
1

我使用類型處理

Spring 3.1.0.RELEASE 

Jackson 1.9.5 

我使用org.springframework.web.client.RestTemplate的getForObject()方法:

getForObject(String url, Class<?> responseType, Map<String, ?> urlVariables) throws RestClientException 

這裏是我的JSON:

{ 
    "someObject": { 
     "someKey": 42, 
    }, 
    "key2": "valueA" 
} 

這裏用於保存它的POJO:

SomeClass.java:

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) 
@Generated("org.jsonschema2pojo") 
@JsonPropertyOrder({ 
    "someObject", 
    "key2" 
}) 

public class SomeClass { 

    @JsonProperty("someObject") 
    private SomeObject someObject; 
    @JsonProperty("key2") 
    private String key2; 

    @JsonProperty("someObject") 
    public LocationInfo getSomeObject() { 
     return someObject; 
    } 

    @JsonProperty("someObject") 
    public void setLocationInfo(SomeObject someObject) { 
     this.someObject = someObject; 
    } 
} 

SomeObject.java:

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) 
@Generated("org.jsonschema2pojo") 
@JsonPropertyOrder({ 
    "someKey" 
}) 

public class SomeObject{ 

    @JsonProperty("someKey") 
    private String someKey; 

    @JsonProperty("someKey") 
    public String getSomeKey() { 
     if(someKey==null){ 
      someKey = ""; 
     } 
     return someKey.toUpperCase(); 
    } 

    @JsonProperty("someKey") 
    public void setSomeKey(String someKey) { 
     this.someKey = someKey; 
    } 

} 

它的工作原理。鑑於JSON結構,我得到一個字符串值爲「42」屬性someKey類SomeObject

我不明白爲什麼。在我不知道的幕後,是否發生了一些神奇的轉變?

轉換可以計算嗎?另外,我目前沒有在字符串someKey的開頭或結尾得到任何空格。這是我可以指望的東西,因爲整數值不能有任何空格?

回答

1

如果你想真正理解它的工作原理,請查看https://github.com/joelittlejohn/jsonschema2pojo的代碼。

是的轉換可以算作,是的,你可以指望他們不是pojo字符串中的空格。

簡而言之,將讀入JSON文件中的字段,然後將這些字段映射到作爲responseType傳入的Pojos的成員變量/設置方法。

+0

非常感謝!對於它的工作方式/原因有簡短的回答嗎?我很好奇,但現在無法讀取代碼。 – user1126515

+0

檢查最新更新 – UserF40

+0

我想我明白了。由於someKey被定義爲一個字符串並且具有註釋@JsonProperty(「someKey」),無論它在JSON中是什麼,它都將在POJO中轉換爲String。是對的嗎? – user1126515