我对JAX-RS相当陌生,请耐心等待这个问题。我正在尝试使用JAX-RS框架使用REST API。特别是,我尝试在响应实体将为JSON格式的资源上调用HTTP GET方法。到目前为止,我可以使用以下代码片段将返回的JSON解析为自定义类;
WebTarget target = client.target(url);
Builder builder = target.request(MediaType.APPLICATION_JSON);
myClass obj = builder.get(myClass.class);
但是,在我最新的GET请求中,最好将JSON返回抽象为一组对象。我知道在.NET中,可以使用
轻松完成此操作JsonConvert.DeserializeObject<List<myClass>>
但是我如何在JAX-RS中做到这一点?预先感谢。
编辑:
我根据How to get list<String> as response from jersey2 client中的解决方案对代码建模
WebTarget target = client.target(url);
Builder builder = target.request(MediaType.APPLICATION_JSON);
builder.header(X_OCTOPUS_APIKEY_NAME, apiKey);
Response serviceResponse = builder.get(Response.class);
List<myType> objects = serviceResponse.readEntity(new GenericType<List<myType>>() {});
但是返回的对象始终为null。为了验证REST API调用实际上返回了有效的JSON值,我将最后一行替换为:
String strDate = serviceResponse.readEntity(String.class);
已通过以下JSON返回确认:
[
{
"Id": "Users-267",
"Username": "[email protected]",
"DisplayName": "Damon, Matt",
"IsActive": true,
"IsService": false,
"EmailAddress": "[email protected]",
"IsRequestor": false,
"Links": {
"Self": "/api/users/Users-267",
"Permissions": "/api/users/Users-267/permissions",
"ApiKeys": "/api/users/Users-267/apikeys{/id}{?skip}",
"Avatar": "https://www.gravatar.com/avatar/94324e7c54a9a5f9d103b2a709863fc3?d=blank"
}
},
{
"Id": "Users-2101",
"Username": "[email protected]",
"DisplayName": "Affleck, Ben",
"IsActive": true,
"IsService": false,
"EmailAddress": "[email protected]",
"IsRequestor": false,
"Links": {
"Self": "/api/users/Users-2101",
"Permissions": "/api/users/Users-2101/permissions",
"ApiKeys": "/api/users/Users-2101/apikeys{/id}{?skip}",
"Avatar": "https://www.gravatar.com/avatar/11edd32712facde9a7d3dd4445a4abe9?d=blank"
}
},
...
]
因此,由于未在我的自定义类型的集合中解析JSON,因此我的习惯定义了另一条信息:
@XmlRootElement
public class myType {
String DisplayName;
String EmailAddress;
public myType() {
super();
}
public void setDisplayName(String displayName) {
DisplayName = displayName;
}
public String getDisplayName() {
return DisplayName;
}
public void setEmailAddress(String emailAddress) {
EmailAddress = emailAddress;
}
public String getEmailAddress() {
return EmailAddress;
}
}
我仅在自定义类型中包含JSON的DisplayName和EmailAddress字段,因为在重要的情况下,我不需要所有其他数据。谁能告诉我为什么它没有被解析?谢谢