原文地址:http://www.studytrails.com/java/json/java-google-json-parse-json-to-java-tree.jsp
在之前的教程中,我們看到怎樣將一段json字符串轉換成Java對象.在這節中,我們將把json轉換成樹結構的JsonElement.遍歷這個樹對象可以生成對應的java對象.JsonElement這個類有isJsonObject(),isJsonNull()等這些用來判斷JsonElement的方法.有getAsJsonObject(),getAsJsonPrimitive()等獲取實際對象的方法.接下來,我們將解析從free music
archiver返回的json,代碼如下:
package com.studytrails.json.gson;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class ParseTreeExample6 {
public static void main(String[] args) throws MalformedURLException, IOException {
String url = "http://freemusicarchive.org/api/get/albums.json?api_key=60BLHNQCAOUFPIBZ&limit=5";
String json = IOUtils.toString(new URL(url));
JsonParser parser = new JsonParser();
// The JsonElement is the root node. It can be an object, array, null or
// java primitive.
JsonElement element = parser.parse(json);
// use the isxxx methods to find out the type of jsonelement. In our
// example we know that the root object is the Albums object and
// contains an array of dataset objects
if (element.isJsonObject()) {
JsonObject albums = element.getAsJsonObject();
System.out.println(albums.get("title").getAsString());
JsonArray datasets = albums.getAsJsonArray("dataset");
for (int i = 0; i < datasets.size(); i++) {
JsonObject dataset = datasets.get(i).getAsJsonObject();
System.out.println(dataset.get("album_title").getAsString());
}
}
}
}