我有一个User类定义为:
User.java
package model;
import java.util.List;
import java.util.Map;
public class User {
private final Map<String, List<String>> accountTransactionsMap;
public User(final Map<String, List<String>> accountTransactionsMap) {
this.accountTransactionsMap = accountTransactionsMap;
}
public Map<String, List<String>> getAccountTransactionsMap() {
return accountTransactionsMap;
}
}
我正在调用返回以下响应的 REST API:
{
"username1":{
"456":[
],
"123":[
],
"789":[
]
},
"username2":{
"123":[
],
"456":[
],
"789":[
]
},
"username3":{
"789":[
],
"123":[
],
"456":[
"transaction10",
"transaction6",
"transaction9",
"transaction3"
]
}
}
我希望能够解析响应并将其存储在User对象中。
我尝试了以下方法:
Test.java
public class Test {
public static void main(final String[] args) {
final String response = "{\"username1\":{\"456\":[],\"123\":[],\"789\":[]},\"username2\":{\"123\":[],\"456\":[],\"789\":[]},\"username3\":{\"789\":[],\"123\":[],\"456\":[\"transaction10\",\"transaction6\",\"transaction9\",\"transaction3\"]}}";
final Gson gson = new Gson();
final Type map = new TypeToken<Map<String, User>>(){}.getType();
final Map<String, User> result = gson.fromJson(response, map);
System.out.println(result);
if (result != null) {
for (final Map.Entry<String, User> entry : result.entrySet()) {
System.out.println("username: " + entry.getKey());
final User user = entry.getValue();
System.out.println("transactions: " + user.getAccountTransactionsMap());
}
}
}
}
这会产生输出:
{username1=model.User@80ec1f8, username2=model.User@1445d7f, username3=model.User@6a396c1e}
username: username1
transactions: null
username: username2
transactions: null
username: username3
transactions: null
繁星淼淼
相关分类