gson是Google提供的一款Java庫,用于將Java對(duì)象轉(zhuǎn)換為JSON格式的數(shù)據(jù)。在開發(fā)中,我們經(jīng)常會(huì)遇到嵌套的JSON格式數(shù)據(jù)需要轉(zhuǎn)換為Java對(duì)象。下面我們來看一個(gè)嵌套JSON轉(zhuǎn)換為list的例子。
String nestedJson = "{"name": "Tom", "age": 20, "hobbies": ["reading", "running", "swimming"], "friends": [{"name": "Lucy", "age": 22}, {"name": "Jack", "age": 23}]}";
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(nestedJson, JsonObject.class);
JsonArray hobbiesJsonArray = jsonObject.getAsJsonArray("hobbies");
List<String> hobbiesList = gson.fromJson(hobbiesJsonArray, List.class);
JsonArray friendsJsonArray = jsonObject.getAsJsonArray("friends");
List<Friend> friendsList = new ArrayList<>();
for (JsonElement friendJsonElement : friendsJsonArray) {
Friend friend = gson.fromJson(friendJsonElement, Friend.class);
friendsList.add(friend);
}
首先,我們將嵌套JSON格式的字符串轉(zhuǎn)換為JsonObject對(duì)象,然后按照數(shù)據(jù)類型將其取出,再使用gson的fromJson()方法將數(shù)據(jù)轉(zhuǎn)換為相應(yīng)的Java對(duì)象。由于hobbies是一個(gè)String類型的數(shù)組,我們可以直接將其轉(zhuǎn)換為List<String>類型;而friends是一個(gè)對(duì)象數(shù)組,我們需要手動(dòng)遍歷數(shù)組并依次將每個(gè)元素轉(zhuǎn)換為相應(yīng)的Friend對(duì)象并添加到List中。
最后,我們可以通過遍歷兩個(gè)List的元素,來訪問具體的數(shù)據(jù):
for (String hobby : hobbiesList) {
System.out.println(hobby);
}
for (Friend friend : friendsList) {
System.out.println("name: " + friend.getName());
System.out.println("age: " + friend.getAge());
}
通過以上方法,我們便可以將嵌套的JSON格式數(shù)據(jù)轉(zhuǎn)換為相應(yīng)的Java對(duì)象,并進(jìn)一步使用這些數(shù)據(jù)。