Gson: Convert json to a java object tree

In the Earlier tutorial we saw how to convert json to a java object. In this tutorial, we build a tree of com.google.gson.JsonElement from the json string. The tree can then be traversed to build java objects. JsonElement has methods such as isJsonObject(), isJsonNull(), etc that can be used to figure out the type of JsonElement. Then to get the actual object use the getAsJsonObject(), getAsJsonPrimitive() etc methods. We parse the response from the free music archive json API. Here’s the class

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());
			}
		}

	}
}

(Note: This article’s original links is here )

 Gson: parsing json to java token by token Gson: Serializing Collections 

Comments

©2015-2021 Alimy All rights reserved.