我在使用漂亮的 Spring Android Rest 客户端模块时遇到问题。 我正在为其余客户端创建响应类型,以便能够将响应解码到对象中。但后来我意识到我不能。 响应包含连字符字段名称,这阻止我使用该字段名称创建一个类。
以下是 JSON 响应的示例:
{
....
created-by: "Wikipedia",
last-updated-by: "Wikipedia",
create-date: "2010-11-21 13:55:37",
last-update-date: "2010-11-21 13:55:37",
...
}
所以在这种情况下我无法上课,例如:
class ResponseType{
private String created-by; //NOT A VALID VARIABLE NAME
...
}
我尝试从许多论坛获得答案,但未能找到解决方案。 我发现很多地方的人都建议在字段上添加注释,例如:
@JsonProperty("created-by")
private String created_by;
但是没有用,因为spring android Rest模板没有这个注解。
我想要实现的是:
String url = "http://mymemory.translated.net/api/get?q=accidentally&langpair=en|hu";
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
ResponseType responseType = restTemplate.getForObject(url, ResponseType.class, "Android");
我很好奇解决方案是什么。期待答案!
最佳答案
终于找到问题了。
问题是 spring android rest 模块有依赖项。尤其是第三方库。
让我粘贴部分文档:
2.2.3 Object to JSON Marshaling Object to JSON marshaling in Spring for Android RestTemplate requires the use of a third party JSON mapping library. There are three libraries supported in Spring for Android, Jackson JSON Processor, Jackson 2.x, and Google Gson. While Jackson is a well known JSON parsing library, the Gson library is smaller, which would result in an smaller Android app when packaged.
关于java - Android Rest 客户端 - JSON 响应中的连字符名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21311483/