反序列化复杂的json主体,验证其中的一个元素,然后通过它映射到另一个元素(JAVA),这可能吗



我有一个json数组可以使用,如下所示:

[
{
"id": "12345",
"eauthId": "123451234512345123451234512345",
"firstName": "Jane",
"middieInitial": "M",
"lastName": "Doe",
"email": "janedoe@usda.gov",
"roles": [
{
"id": "CTIS_ROLE_ID",
"name": "A test role for CTIS",
"treatmentName": "Fumigation"
}
]
},
{
"id": "67890",
"eauthId": "678906789067890678906789067890",
"firstName": "John",
"middieInitial": "Q",
"lastName": "Admin",
"email": "johnadmin@usda.gov",
"roles": [
{
"id": "CTIS_ADMIN",
"name": "An admin role for CTIS",
"treatmentName": "System Administration"
}
]
}
]

我的任务是找出用户的";角色"-->quot;name";,匹配后,获取该用户的电子邮件地址并使用该电子邮件地址登录。这似乎是一项简单的任务,但它真的让我大吃一惊,因为深入研究API对我来说是新的。我尝试过不同的库(Jackson、RestAssured、Json simple(,最后是GSon。我没有时间坐下来从头开始研究每件事。我只是需要一个快速的解决方案。但肯定不是很快。有人好心帮我解决这个问题吗。我真的很感激。

closeableHttpResponse = restClient.get(ConfigurationReader.get("base_url") + ConfigurationReader.get("user_endpoint"));
//Status code
int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
System.out.println("statusCode = " + statusCode);
String responseString = EntityUtils.toString(closeableHttpResponse.getEntity(), "UTF-8");
Type userListType = new TypeToken<List<Users>>(){}.getType(); 
List<Users> users = (List<Users>) new Gson().fromJson(responseString, userListType); 
Roles roles = new Gson().fromJson(responseString, Roles.class); 

它给了我这个错误

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226)
at com.google.gson.Gson.fromJson(Gson.java:932)

代码的问题是

Type userListType = new TypeToken<List>(){}.getType();
List users = (List) new Gson().fromJson(responseString, userListType);

您接收的不仅仅是一个列表,实际上是在反序列化一个列表数组。

所以试试这个:

List[] users = (List[]) new Gson().fromJson(responseString, List[].class);

最新更新