Monday, February 12, 2018

JSON Array parsing in java

package App;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

public class App {
public static void main(String[] args) throws Exception {

URL url = new URL(
"http://openweathermap.org/data/2.5/weather?lat=17&lon=75&appid=b6907d289e10d714a6e88b30761fae22");

URLConnection con = url.openConnection();

BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));

JSONObject obj = (JSONObject) JSONValue.parseWithException(br);

JSONObject sys = (JSONObject) obj.get("sys");

// JSON ARRAY retrives the array

JSONArray weather = (JSONArray) obj.get("weather");

// First line of array and make JSON Object
JSONObject arr = (JSONObject) weather.get(0);

// Get by Key
String desc = (String) arr.get("description");

// Show
System.out.println(desc);

// JSONOBJECTS
long sunrise = (long) sys.get("sunrise");

long sunset = (long) sys.get("sunset");

double message = (double) sys.get("message");

String country = (String) sys.get("country");

br.close();

}

}