2016-07-26 62 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