com.easycode.visualisation_1.JSONParser.java Source code

Java tutorial

Introduction

Here is the source code for com.easycode.visualisation_1.JSONParser.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.easycode.visualisation_1;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 *
 * @author Luuk
 */
public class JSONParser {
    private JsonObject rootobj = new JsonObject();

    public JsonObject getJsonFromUrl(String sUrl) throws MalformedURLException, IOException {

        // Connect to the URL using java's native library
        URL url = new URL(sUrl);
        HttpURLConnection request = (HttpURLConnection) url.openConnection();
        request.connect();

        // Convert to a JSON object to print data
        JsonParser jp = new JsonParser(); //from gson
        JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
        this.rootobj = root.getAsJsonObject(); //May be an array, may be an object. 

        return rootobj;
    }
}