【发布时间】:2015-11-01 13:55:50
【问题描述】:
我是 Java 新手。我正在使用 Spring 来使用输出 JSON 的 REST api。通过 Spring 网站上的教程,我可以轻松地将 JSON 响应转换为所需类的对象。现在的问题是 JSON 响应中的一个键是$id。我不能创建一个带有美元符号的变量。我假设我应该在某处定义一些配置,以便将这样的名称转换为可接受的名称。我不知道怎么做。
我的休息请求代码:
protected LoginResult doInBackground(Void... params) {
try {
Log.i(TAG, "Making Login request");
//TODO: Make this a setting
final String url = "https://someurl.com/api/login";
LoginCredentials login = new LoginCredentials("foo@bar.com", "qwerty123");
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
LoginResult result = restTemplate.postForObject(url, login, LoginResult.class);
Log.d(TAG, "Got the LoginResult.");
return result;
} catch (Exception e) {
//TODO: Exception handling
Log.e(TAG, e.getMessage(), e);
}
return null;
}
生成的 JSON 如下所示:
{
"_id":{
"$id":"98765432"
},
"name":"Person Guy",
"email":"foo@bar.com",
"roles":[
"user"
],
"active":true,
"created":{
"sec":1439117849,
"usec":856000
},
"session":{
"token":"12345678",
"user_id":"98765432",
"created":{
"sec":1439134272,
"usec":0
},
"last_extended":{
"sec":1439134272,
"usec":0
},
"expires":{
"sec":1439998272,
"usec":0
}
}
}
$id 部分是事情变得困难的地方。 LoginResult 类如下所示:
@JsonIgnoreProperties(ignoreUnknown = true)
public class LoginResult {
private String name;
private String email;
private MongoId _id;
/* Getters and setters */
}
MongoId 类如下所示(现在添加了JsonIgnoreProperties 以避免异常):
@JsonIgnoreProperties(ignoreUnknown = true)
public class MongoId {
private String id; //This is $id in the JSON response.
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
任何帮助将不胜感激。
【问题讨论】:
-
我怀疑 $ 是否有问题。
-
@Garry 在 Android Studio 中使用 $ in 变量会给我各种错误。此外,Java 似乎不鼓励在其文档中的变量中使用 $ 符号。