Not able to print json object in a json array - java

This is the json I'm working with. I need to print description object which is inside weather array. I am getting JSONArray[2] not found exception while compiling. I'm using java-json.
{
"coord": {
"lon": 72.85,
"lat": 19.01
},
"weather": [
{
"id": 721,
"main": "Haze",
"description": "haze",
"icon": "50n"
}
],
"base": "stations",
"main": {
"temp": 303.15,
"pressure": 1009,
"humidity": 74,
"temp_min": 303.15,
"temp_max": 303.15
},
"visibility": 3000,
"wind": {
"speed": 2.1,
"deg": 360
},
"clouds": {
"all": 20
},
"dt": 1539273600,
"sys": {
"type": 1,
"id": 7761,
"message": 0.0642,
"country": "IN",
"sunrise": 1539219701,
"sunset": 1539262109
},
"id": 1275339,
"name": "Mumbai",
"cod": 200
}
this is the code--
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
import org.json.JSONArray;
class Send_HTTP_Request2 {
public static void main(String[] args) {
try {
Send_HTTP_Request2.call_me();
} catch (Exception e) {
e.printStackTrace();
}
}
static void call_me() throws Exception {
String url = "http://api.openweathermap.org/data/2.5/weather?id=1275339&APPID=77056fb4e0ba03b117487193c37c90d2";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSONObject myResponse = new JSONObject(response.toString());
JSONArray jrr= myResponse.getJSONArray("weather");
System.out.println("CITY-"+myResponse.getString("name"));
JSONObject desc = jrr.getJSONObject(2);
System.out.println(desc);
}
}

For the JSONArray method of getJSONObject(int index) (Link to the Javadoc here)
You're right to grab the JSONObject inside of the array, but you're grabbing the wrong index, which in this case, is 0 since in Java, index 0 is the first item of the array. (More on Arrays and indexes here)
And then you would just call desc.getString("description") and assign it to a String, since the description key is a String type.
So more specifically you'd do something link this (assuming we're not checking for nulls or iterating through the array with a for loop or anything):
JSONObject myResponse = new JSONObject(response.toString());
JSONArray jrr= myResponse.getJSONArray("weather");
System.out.println("CITY-"+myResponse.getString("name"));
JSONObject weatherObj = jrr.getJSONObject(0);
String desc = weatherObj.getString("description");
System.out.println(desc);
Hope this helps!
Edited for formatting

Related

Json Object not Displaying in Java

I want to get "weather" data from JSONObject but this error is coming.
org.json.JSONException: JSONObject["weather"] not a string.
at org.json.JSONObject.getString(JSONObject.java:639)
at GetWeather.main(GetWeather.java:49)
This is my code
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class GetWeather {
public static String getWeather(String args){
String result =" ";
URL url ;
HttpURLConnection urlConnection = null;
try{
url = new URL(args);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data= reader.read();
while(data!=-1){
char current=(char) data;
result += current;
data= reader.read();
}
return result;
}catch(MalformedURLException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//main
public static void main(String[] args){
String s1 = getWeather(args[0]);
try {
JSONObject jsonObject = new JSONObject(s1);
String weather= jsonObject.getString("weather");
System.out.println(weather);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This is the string which I am passing
http://api.openweathermap.org/data/2.5/weather?q=Delhi&APPID=04b767167643ea6af521695e7948e0fb
This is the data I get back
{"coord":{"lon":77.22,"lat":28.67},"weather":[{"id":721,"main":"Haze","description":"haze","icon":"50d"}],"base":"stations","main":{"temp":305.86,"pressure":1007,"humidity":38,"temp_min":304.15,"temp_max":307.15},"visibility":3500,"wind":{"speed":1.5,"deg":320},"clouds":{"all":0},"dt":1508241600,"sys":{"type":1,"id":7808,"message":0.0051,"country":"IN","sunrise":1508201604,"sunset":1508242734},"id":1273294,"name":"Delhi","cod":200}
Which in formatted version looks like
{
"coord": {
"lon": 77.22,
"lat": 28.67
},
"weather": [{
"id": 721,
"main": "Haze",
"description": "haze",
"icon": "50d"
}
],
"base": "stations",
"main": {
"temp": 305.86,
"pressure": 1007,
"humidity": 38,
"temp_min": 304.15,
"temp_max": 307.15
},
"visibility": 3500,
"wind": {
"speed": 1.5,
"deg": 320
},
"clouds": {
"all": 0
},
"dt": 1508241600,
"sys": {
"type": 1,
"id": 7808,
"message": 0.0051,
"country": "IN",
"sunrise": 1508201604,
"sunset": 1508242734
},
"id": 1273294,
"name": "Delhi",
"cod": 200
}
Please tell me whats wrong with my code and what to do.
The value of "weather" that you're trying to get is not a String, but a JSONArray.
In order to read all the information inside it, try using getJSONArray():
try {
JSONObject jsonObject = new JSONObject(s1);
// read the `weather` content
JSONArray weatherArray = jsonObject.getJSONArray("weather");
// get only the first element of `weather`, the only one existing
JSONObject weatherObject = (JSONObject)weatherArray.get(0);
// read all its' properties
for (Object key : weatherObject.keySet()) {
System.out.println("key:" + key + ", value: " + weatherObject.get((String)key));
}
} catch (JSONException e) {
e.printStackTrace();
}
For other info like "temp" or "pressure", just use getJSONObject() since "main" has JSONObject type:
JSONObject mainObject = jsonObject.getJSONObject("main");
System.out.println("pressure value: " + mainObject.get("pressure"));
System.out.println("temp value: " + mainObject.get("temp"));

How to parse JSON on Java

I have the following JSON text that I need to parse to get "id": 176514,
What is the required code?
{
"response": {
"count": 10307,
"items": [
{
"id": 176514,
"from_id": -114200945,
"owner_id": -114200945,
"date": 1506629224,
"marked_as_ads": 0,
"post_type": "post",
"text": "-я с разбитым сердцем сука,но я всё равно влюблённый.",
"post_source": {
"type": "api"
},
"comments": {
"count": 1,
"groups_can_post": true,
"can_post": 1
},
"likes": {
"count": 103,
"user_likes": 0,
"can_like": 1,
"can_publish": 1
},
"reposts": {
"count": 3,
"user_reposted": 0
},
"views": {
"count": 1022
}
}
]
}
}
I try some times but.. (
my code
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
import org.json.JSONArray;
import org.json.JSONObject;
class VK{
public static void main(String [] args) throws IOException{
URL url = new URL("my url which return JSON structure");
Scanner scan = new Scanner(url.openStream());
String str = new String();
while (scan.hasNext())
str += scan.nextLine();
scan.close();
JSONObject obj = new JSONObject(str);
JSONObject res = obj.getJSONArray("items").getJSONObject(0);
System.out.println(res.getInt("id"));
}
}
Eclipse
my errors:
Exception in thread "main" org.json.JSONException: JSONObject["items"] not found.
at org.json.JSONObject.get(JSONObject.java:472)
at org.json.JSONObject.getJSONArray(JSONObject.java:619)
at VK.main(VK.java:26)
You need to go one more level deep.
JSONObject obj = new JSONObject(str);
JSONObject firstItem = obj.getJSONObject("response").getJSONArray("items").getJSONObject(0);
System.out.println(firstItem.getInt("id"));
try this:
JSONObject obj = new JSONObject(str);//assuming that obj is the same object as in the example
//to get the id
int id = obj.getJSONObject("response").getJSONArray("items").getJSONObject(0).getInt("id");
In case that you are parsing Array of objects
JSONArray jsonArray = new JSONArray(stringToParse);
than continue as usual

How to make a dictionary application using Oxford Dictionary api?

This is the code which I got from the documentations, I get that, I receive the result in JSON format. But I only need the meaning of the word. So can anyone tell me how do I extract only the meaning of the searched word, rather getting the whole JSON file. I am new to android development, Please help me.
package com.example.hsekar.dictionarytestbeta;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new CallbackTask().execute(dictionaryEntries());
}
private String dictionaryEntries() {
final String language = "en";
final String word = "Ace";
final String word_id = word.toLowerCase(); //word id is case sensitive and lowercase is required
return "https://od-api.oxforddictionaries.com:443/api/v1/entries/" + language + "/" + word_id;
}
//in android calling network requests on the main thread forbidden by default
//create class to do async job
private class CallbackTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
//TODO: replace with your own app id and app key
final String app_id = "10742428";
final String app_key = "ada344f3a7a7c7de0315fb78c5c9d6f9";
try {
URL url = new URL(params[0]);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestProperty("Accept","application/json");
urlConnection.setRequestProperty("app_id",app_id);
urlConnection.setRequestProperty("app_key",app_key);
// read the output from the server
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
return stringBuilder.toString();
}
catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("This will be my result",result);
}
}
}
The following is my output. I am just printing it in the Logcat but once I get the concept , I will start working on the project.
This will be my result: {
"metadata": {
"provider": "Oxford University Press"
},
"results": [
{
"id": "ace",
"language": "en",
"lexicalEntries": [
{
"entries": [
{
"etymologies": [
"Middle English (denoting the ‘one’ on dice): via Old French from Latin as ‘unity, a unit’"
],
"grammaticalFeatures": [
{
"text": "Singular",
"type": "Number"
}
],
"homographNumber": "000",
"senses": [
{
"definitions": [
"a playing card with a single spot on it, ranked as the highest card in its suit in most card games"
],
"domains": [
"Cards"
],
"examples": [
{
"registers": [
"figurative"
],
"text": "life had started dealing him aces again"
},
{
"text": "the ace of diamonds"
}
],
"id": "m_en_gbus0005680.006"
},
{
"definitions": [
"a person who excels at a particular sport or other activity"
],
"domains": [
"Sport"
],
"examples": [
{
"text": "a motorcycle ace"
}
],
"id": "m_en_gbus0005680.010",
"registers": [
"informal"
],
"subsenses": [
{
"definitions": [
"a pilot who has shot down many enemy aircraft"
],
"domains": [
"Air Force"
],
"examples": [
{
"text": "a Battle of Britain ace"
}
],
"id": "m_en_gbus0005680.011"
}
]
},
{
"definitions": [
"(in tennis and similar games) a service that an opponent is unable to return and thus wins a point"
],
"domains": [
"Tennis"
So my question is how do I extract only the 'meaning' part from this output?
The Json result that you have mentioned is incomplete.the objects in the result are not closed.By the way this is how you get the results from json string.
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject js = new JSONObject(result);
JSONArray results = js.getJSONArray("results");
for(int i = 0;i<results.length();i++){
JSONObject lentries = results.getJSONObject(i);
JSONArray la = lentries.getJSONArray("lexicalEntries");
for(int j=0;j<la.length();j++){
JSONObject entries = la.getJSONObject(j);
JSONArray e = entries.getJSONArray("entries");
for(int i1=0;i1<e.length();i1++){
JSONObject senses = la.getJSONObject(i1);
JSONArray s = entries.getJSONArray("senses");
JSONObject d = s.getJSONObject(0);
JSONArray de = d.getJSONArray("definitions");
def = de.getString(0);
}
}
}
Log.e("def",def);
} catch (JSONException e) {
e.printStackTrace();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Log.d("This will be my result",result);
String def = "";
try {
JSONObject js = new JSONObject(result);
JSONArray results = js.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject lentries = results.getJSONObject(i);
JSONArray la = lentries.getJSONArray("lexicalEntries");
for (int j = 0; j < la.length(); j++) {
JSONObject entries = la.getJSONObject(j);
JSONArray e = entries.getJSONArray("entries");
for (int k= 0; k < e.length(); k++) {
JSONObject senses = e.getJSONObject(k);
JSONArray s = senses.getJSONArray("senses");
JSONObject d = s.getJSONObject(0);
JSONArray de = d.getJSONArray("definitions");
def = de.getString(0);
}
}
}
Log.e("def", def);
} catch (JSONException e) {
e.printStackTrace();
}
//Log.d("This will be my result",result);
}

Exception Cast JsonObject

How can I read this file using JsonObject and JsonArray? And how can I retrieve the typeId value?
{
"mockup": {
"controls": {
"control": [
{
"ID": "5",
"measuredH": "400",
"measuredW": "450",
"properties": {
"bold": "true",
"bottomheight": "0",
"italic": "true",
"size": "20",
"text": "Test",
"topheight": "26",
"underline": "true",
"verticalScrollbar": "true"
},
"typeID": "TitleWindow",
"x": "50",
"y": "50",
"zOrder": "0"
},
{
"ID": "6",
"measuredH": "27",
"measuredW": "75",
"properties": {
"align": "left",
"bold": "true",
"color": "0",
"italic": "true",
"menuIcon": "true",
"size": "18",
"state": "selected",
"text": "OK",
"underline": "true"
},
"typeID": "Button",
"x": "67",
"y": "85",
"zOrder": "1"
}
]
},
"measuredH": "450",
"measuredW": "500",
"mockupH": "400",
"mockupW": "450",
"version": "1.0"
}
}
I'm using this code:
import org.json.JSONException;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Main {
private static final String _strDesktopDirectory = System.getProperty("user.home") + "/Desktop";
public static void main(String[] args) {
JSONParser _jspMyJsonParser = new JSONParser();
JFileChooser _fcMyFileChooser = new JFileChooser("Open JSON File");
FileNameExtensionFilter _fneJsonFilter = new FileNameExtensionFilter("JSON Files (*.json)", "json");
_fcMyFileChooser.setFileFilter(_fneJsonFilter);
int _iReturnFile = _fcMyFileChooser.showOpenDialog(_fcMyFileChooser);
_fcMyFileChooser.setCurrentDirectory(new File(_strDesktopDirectory));
if (_iReturnFile == JFileChooser.APPROVE_OPTION) {
try {
String _strSelectedFile = _fcMyFileChooser.getSelectedFile().toString();
Object _oMyObject = _jspMyJsonParser.parse(new FileReader(_strSelectedFile));
// Exception Here.
JSONObject _jsnoMockup = (JSONObject) _oMyObject;
_jsnoMockup = (JSONObject) _jsnoMockup.get("mockup");
JSONObject _jsnoControls = (JSONObject) _jsnoMockup.get("controls");
System.out.println("Mockup: " + _jsnoMockup);
System.out.println("Controls: " + _jsnoControls);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
} else {
System.out.println("Close");
System.exit(0);
}
}
}
The error is:
Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.JSONObject
Note: I don't have any experience with Java.
The method getJSONfromURL returns the JSON of the given URL and that works just fine but the error is in JSONArray jsonArray = (JSONArray)jsonobject;
It gives the following error: cannot cast JSONObject to JSONArray. I've also tried this: JSONArray jsonArray = (JSONObject)(JSONArray)jsonobject;
I can't figure out what I'm doing wrong.
try with below one
JSONArray jsonArray = new JSONArray();
jsonArray = jsonObject.getJSONObject("mockup").getJSONObject("controls").getJSONArray("control");
for(i=0;i<jsonArray.lenght();i++){
System.out.println(jsonArray.getJSONObject(i).getString("typeID"));
}

Getting JSON value from HTTP Request using GSON with Java

I need to get the lat and lng cords as separate string values. I decided to use GSON to help with this but am having issues getting the points. I'd prefer not to add any extra classes but it's not a deal breaker. I don't even care to use an easier solution without GSON if there is one.
Below is what I tried.
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws InterruptedException, IOException, JSONException {
JSONObject json = readJsonFromUrl("http://open.mapquestapi.com/geocoding/v1/address?key=Fmjtd|luu821ual9,8w=o5-94aaqy&location=1448south4thstreetlouisvilleky");
System.out.println(json.toString());
System.out.println(json.get("results"));
}
I can get the results string but not just the lat or lng. Plus it uses extra classes I was trying to avoid. Below is what the JSON returned from the URL looks like.
{
"info": {},
"options": {},
"results": [
{
"providedLocation": {
"location": "address here"
},
"locations": [
{
"street": "address here",
"adminArea6": "",
"adminArea6Type": "Neighborhood",
"adminArea5": "city name",
"adminArea5Type": "City",
"adminArea4": "County name",
"adminArea4Type": "County",
"adminArea3": "State name",
"adminArea3Type": "State",
"adminArea1": "US",
"adminArea1Type": "Country",
"postalCode": "zip here",
"geocodeQualityCode": "P1AAX",
"geocodeQuality": "POINT",
"dragPoint": false,
"sideOfStreet": "N",
"linkId": "0",
"unknownInput": "",
"type": "s",
"latLng": {
"lat": 90.227222,
"lng": -90.762007
},
"displayLatLng": {
"lat": 90.227222,
"lng": -90.762007
},
"mapUrl": "http://open.mapquestapi.com/staticmap/v4/getmap?key=111111111,160&pois=purple4"
}
]
}
]
}
JsonParser parser = new JsonParser();
JsonObject o = parser.parse(jsonStr).getAsJsonObject();
JsonElement latLng = o.get("results")
.getAsJsonArray().get(0)
.getAsJsonObject().get("locations")
.getAsJsonArray().get(0)
.getAsJsonObject().get("latLng");
Parse json String as Jsonobject, and get value one by one. but I think the fastest way is creating a model to map the Json String Object.

Categories

Resources