HTTP请求GET方法。如何在Java中的Spring RestTemplate(getForEntity)+ JSON上解决此问题?

时间:2018-08-06 11:04:34

标签: java json spring rest

  

我想通过一个攻击Codewars API的库以JSON格式检索我的用户的信息。请求方法(GET,将有关用户信息的JSON返回给您)https://www.codewars.com/api/v1/users/(here,您输入了用户名)首先,我在此URI的末尾添加了我的名字,以检查它是否可以正常工作并返回JSON。之后,我使用了一个转换器(JSON到Java)来获取与JSON相对应的Java代码。 http://www.jsonschema2pojo.org/
  我的JSON:

 {
username: "heremyusername",
name: null,
honor: 2,
clan: "pepito",
leaderboardPosition: 500793,
skills: null,
ranks: {
overall: {
rank: -8,
name: "8 kyu",
color: "white",
score: 2
},
languages: {
java: {
rank: -8,
name: "8 kyu",
color: "white",
score: 2
}
}
},
codeChallenges: {
totalAuthored: 0,
totalCompleted: 1
}
 }
  

我的方法:

public User getUser() {
RestTemplate restTemplate = new RestTemplate();
User user = restTemplate.getForEntity("https://www.codewars.com/api/v1/users/(here my user name)", User.class).getBody();
return  ;
}
  

问题是JSON to Java给了我6种不同的Java类。其中之一:

package entities;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)

@JsonPropertyOrder({
"overall",
"languages"
})

public class Ranks {

@JsonProperty("overall")
private Overall overall;

@JsonProperty("languages")
private Languages languages;

@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, 
Object>(); 


@JsonProperty("overall")
public Overall getOverall() {
return overall;
}

@JsonProperty("overall")
public void setOverall(Overall overall) {
this.overall = overall;
}

@JsonProperty("languages")
public Languages getLanguages() {
return languages;
}

@JsonProperty("languages")
public void setLanguages(Languages languages) {
this.languages = languages;
}

@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

}
  

它还给我又另一个5个Java类(Java,Overall,Mail,Languages,CodeChallenge),它们的格式相同(getter,setters ...),因此方法public User getUser()错了,我不知道它是什么返回,如果我必须使它无效或使用什么类,因为我想检索所有信息而不仅是一部分。
  User是一个JavaBean,其字段为Integer id和String用户名。

0 个答案:

没有答案