Cannot parse JSONArray using GSON - java

I have encountered a problem whilst developing my Android application. My problem is that I don't know how to parse JSON code from an URL using GSON. I searched Google and SO for about an hour or so, but nothing worked for me. Everything I found on the internet referred to custom JSON code, not code from an URL. Here is a small sample of the data I have.
{
"status": {
"error": "NO",
"code": 200,
"description": "none",
"message": "Request ok"
},
"geoLocation": {
"city_id": "147",
"city_long": "Saint-Laurent",
"region_short": "QC",
"region_long": "Quebec",
"country_long": "Canada",
"country_id": "43",
"region_id": "35"
},
"stations": [
{
"country": "Canada",
"price": "3.65",
"address": "3885, Boulevard Saint-Rose",
"diesel": "0",
"id": "33862",
"lat": "45.492367",
"lng": "-73.710915",
"station": "Shell",
"region": "Quebec",
"city": "Saint-Laurent",
"date": "3 hours agp",
"distance": "1.9km"
},
{
"country": "Canada",
"price": "3.67",
"address": "3885, Saint-Mary",
"diesel": "0",
"id": "33872",
"lat": "45.492907",
"lng": "-73.740715",
"station": "Shell",
"region": "Quebec",
"city": "Saint-Laurent",
"date": "3 hours agp",
"distance": "2.0km"
}
]
}
I am a beginner at JSON/GSON so I need a bit of help. Here is what I have:
try {
String sURL = "http://api.mygasfeed.com/stations/radius/(39.631439)/(-80.8005451)/(25)/reg/(price)/uc82wk25m0.json?callback=?";
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
JsonObject rootobj = root.getAsJsonObject(); //may be an array, may be an object.
longitude = rootobj.get("price").getAsString();
latitude = rootobj.get("address").getAsString();
} catch (Exception e) {
e.printStackTrace();
}
I tried a loop to parse the array but that failed miserably. Any help regarding this problem is highly appreciated.
------------------------------EDIT-----------------------------------------------
I am extremely sorry about the incorrrect JSON code. I have updated the code but still cannot figure out the solution.

You JSON is wrong:
"date": "3 hours agp",
"distance": "1.9km"
}
{
"country": "Canada",
To coorect it, you must add a ,
"date": "3 hours agp",
"distance": "1.9km"
},
{
"country": "Canada",

Try this, using the basic org.json.JSONObject and org.json.JSONArray it works fine for me...
// This string is the JSON you gave as imput
String json = "{ \"status\": { \"error\": \"NO\", \"code\": 200, \"description\": \"none\", \"message\": \"Request ok\" }, \"geoLocation\": { \"city_id\": \"147\", \"city_long\": \"Saint-Laurent\", \"region_short\": \"QC\", \"region_long\": \"Quebec\", \"country_long\": \"Canada\", \"country_id\": \"43\", \"region_id\": \"35\" }, \"stations\": [ {\"country\": \"Canada\",\"price\": \"3.65\",\"address\": \"3885, Boulevard Saint-Rose\",\"diesel\": \"0\",\"id\": \"33862\",\"lat\": \"45.492367\",\"lng\": \"-73.710915\",\"station\": \"Shell\",\"region\": \"Quebec\",\"city\": \"Saint-Laurent\",\"date\": \"3 hours agp\",\"distance\": \"1.9km\" }, {\"country\": \"Canada\",\"price\": \"3.67\",\"address\": \"3885, Saint-Mary\",\"diesel\": \"0\",\"id\": \"33872\",\"lat\": \"45.492907\",\"lng\": \"-73.740715\",\"station\": \"Shell\",\"region\": \"Quebec\",\"city\": \"Saint-Laurent\",\"date\": \"3 hours agp\",\"distance\": \"2.0km\" } ]}";
try{
JSONObject rootobj = new JSONObject(json);
JSONArray array = rootobj.getJSONArray("stations");
for( int i = 0; i < array.length(); i++){
JSONObject o = array.getJSONObject(i);
String price = o.getString("price");
String address = o.getString("address");
//...
}
}catch(JSONException jse){
// Manage Exception here
}

Try below code to fetch data from url and parse the response using Gson.
Note : Remove "?callback=?" from your url, that will remove "?(" from your response
try {
String sURL = "http://api.mygasfeed.com/stations/radius/(39.631439)/(-80.8005451)/(25)/reg/(price)/uc82wk25m0.json";
URL u = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) u.openConnection();
request.setRequestMethod("GET");
request.connect();
int status = request.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
JsonElement element = new Gson().fromJson (br, JsonElement.class);
JsonObject jsonObj = element.getAsJsonObject();
JsonArray jArray = jsonObj.get("stations").getAsJsonArray();
for (int i = 0, size = jArray.length(); i < size; i++) {
JSONObject jObj = jArray.getJSONObject(i);
System.out.println(" Price : " + jObj.get("price").toString());
System.out.println(" Address : " + jObj.get("address").toString());
}
}
} catch (MalformedURLException ex) {
// Manage Exception here
} catch (IOException ex) {
// Manage Exception here
}

Related

What is the best way to extract data from this JSON string? [duplicate]

I have some trouble with parsing a JSON response. The response data:
{
"deal": {
"categorie": {
"description": "Offres Shopping",
"idcategorie": "1",
"nom": "Shopping"
},
"conditions": "2 personne au plus",
"dateAjout": "2013-01-07T00:00:00+01:00",
"dateExp": "2013-01-31T00:00:00+01:00",
"description": "nuit dans un hotel 5 etoile",
"heurexp": "12",
"iddeal": "1",
"minutesexp": "30",
"prestataire": {
"adresse": "Qu zohour 44",
"codePostale": "12600",
"description": "Hotel 5 etoiles",
"idprestataire": "1",
"nom": "Hotel ronald",
"pays": "France",
"telephone": "99999999",
"ville": "Brest"
},
"prix": "80.0",
"prixHabituel": "200.0",
"tags": "hotel",
"titre": "Nuit 5 etoiles"
}
}
When trying to parse this response to a List<Deal> I get this exception:
com.google.gson.JsonObject cannot be cast to com.google.gson.JsonArray
This is the code that I am using for the parse:
if (reponse != null && !reponse.isEmpty()) {
System.out.println(reponse);
Gson g = new Gson();
JsonParser parser = new JsonParser();
JsonObject jObject = parser.parse(reponse).getAsJsonObject();
JsonArray jArray = jObject.getAsJsonArray("deal"); // here goes the Exception
for (JsonElement elem : dealArray) {
deals.add(g.fromJson(elem, Deal.class));
}
System.out.println(deals.toString());
return "success";
}
thanks
Well, deal is not a JSON array, its a JSON object. Hence the exception. A JSON array, for reference, would look more like this:
"deal" : [{"attr" : "value"}, {"attr" : "value"}]

org.json.JSONObject creating JSONObject from string threw java.lang.RuntimeException

I've been trying to figure out why constructing a org.json.JSONObject from a string json would not work for very long.
Here is the json string (pretty)
{
"status": 200,
"message": "200 Request is valid",
"job": {
"Id": 1,
"Jobtitle": "Test Job",
"Description": "Asthma",
"Medicalcondition": "Asthma",
"Language": "English",
"Racereligion": "Chinese",
"Agegender": "50, Female",
"Hourlyprice": 42,
"Type": "caregiver",
"Date": "2019-05-12T00:00:00+08:00",
"Starttime": "2018-07-20T12:15:00+08:00",
"Endtime": "2018-07-20T18:15:00+08:00",
"Address": "1 Cluny Road",
"Latitude": 1.3152057,
"Longitude": 103.8162553,
"Creator": "xiurobert"
}
}
and minified (the one that I'm attempting to construct a JSONObject from)
String json = "{\"status\":200,\"message\":\"200 Request is valid\",\"job\":{\"Id\":1,\"Jobtitle\":\"Test Job\",\"Description\":\"Asthma\",\"Medicalcondition\":\"Asthma\",\"Language\":\"English\",\"Racereligion\":\"Chinese\",\"Agegender\":\"50, Female\",\"Hourlyprice\":42,\"Type\":\"caregiver\",\"Date\":\"2019-05-12T00:00:00+08:00\",\"Starttime\":\"2018-07-20T12:15:00+08:00\",\"Endtime\":\"2018-07-20T18:15:00+08:00\",\"Address\":\"1 Cluny Road\",\"Latitude\":1.3152057,\"Longitude\":103.8162553,\"Creator\":\"xiurobert\"}}";
Constructor
JSONObject jsonObject = new JSONObject(json)
However, this resulted in a java.lang.RuntimeException: Cannot evaluate org.json.JSONObject.toString()
I've even tried using gson to parse the string first and then output it back to the new JSONObject but it seems like it didn't work.
Any reasons why?
This is working perfectly
String json = "{\"status\":200,\"message\":\"200 Request is valid\",\"job\":{\"Id\":1,\"Jobtitle\":\"Test Job\",\"Description\":\"Asthma\",\"Medicalcondition\":\"Asthma\",\"Language\":\"English\",\"Racereligion\":\"Chinese\",\"Agegender\":\"50, Female\",\"Hourlyprice\":42,\"Type\":\"caregiver\",\"Date\":\"2019-05-12T00:00:00+08:00\",\"Starttime\":\"2018-07-20T12:15:00+08:00\",\"Endtime\":\"2018-07-20T18:15:00+08:00\",\"Address\":\"1 Cluny Road\",\"Latitude\":1.3152057,\"Longitude\":103.8162553,\"Creator\":\"xiurobert\"}}";
try
{
JSONObject jsonObject = new JSONObject(json);
Log.i("TAG", "a: "+jsonObject.toString());
} catch (JSONException e)
{
e.printStackTrace();
}
where are you getting error
In my case i have used org.json.JSONObject and org.json.JSONArray. Then i changed the imports to org.json.simple.JSONObject and org.json.simple.JSONArray and my code worked without any issues.

should value must be quoted in JSON along with key

i have data
like this:
{
"status": "success",
"message": "Student Statement Report",
"data": {
"data": [{
"id": "45",
"transaction_no": "45",
"transaction_date": "2017-05-25",
"transaction_type": "invoice",
"transaction_amount": "1010.00",
"related_invoice_id": "45",
"balance_amount": "1010.00",
"related_user_id": "436",
"related_user_group": "student",
"description": "",
"created_by": "Principal",
"updated_by": "Principal",
"created_at": "2017-05-25 11:57:39",
"updated_at": "2017-05-25 11:57:39"
}],
"opening_balance": 0,
"dates": ["2017-05-22 00:00:00", "2017-05-28 23:59:59"]
}
}
JSONObject jsonObject = new JSONObject(response);
and i am geeting Json expection error from here
String openingBalance = jsonObject.getString("opening_balance");
"opening_balance": 0,
so, my biggest question is should that zero (value) should be quoted or not?
You have to parse it like this:
JSONObject jsonObject = new JSONObject(response);
JSONObject data = jsonObject.getJSONObject("data");//Get Data object
int openingBalance = data.getInt("opening_balance");//Get opening balance
If you read the number as an Integer then quotation is not necessary. But if your read it as a String then you have to put quotation.
To read as an Integer you can use getInt("json_key")
& for String getString("json_key").
JSONObject jsonObject = new JSONObject(response);
JSONObject data = jsonObject.getJSONObject("data");//Get Data object
int openingBalance = data.getInt("opening_balance");//Get opening balance

Parsing jsonobject when entire json is an array?

I am using gson-2.5 for this. There is a slight difference in the format of these two jsons, where in the first one;
"usethis": [
{
"id": 111,
"text": "some text that i would like",
},
{
"id": 222,
"text": "someothertextiwouldlike",
}
]
I would have parsed this to get "text" this way, and everything would be ok;
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(listcontents);
JsonObject rootobj = root.getAsJsonObject();
JsonArray items = rootobj.get("usethis").getAsJsonArray();
for(int i = 0; i < items.size(); i++) {
JsonObject item = items.get(i).getAsJsonObject();
String thetext = item.get("text").getAsString();
System.out.println("text: " + thetext + "\n");
}
The difference is that in the second one, I have nothing to get as the rootobject unlike in the first where I used "usethis";
[
{
"id": 111,
"text": "some text that i would like",
},
{
"id": 222,
"text": "someothertextiwouldlike",
}
]
And setting
rootobj.get("usethis").getAsJsonArray();
to
rootobj.get("").getAsJsonArray();
just gives me an error. How would I be able to parse the second json?
JsonElement is just a superclass of JsonArray and JsonObject.
JsonArray items = root.getAsJsonArray();
should do what you want.

android get duration from maps.google.com directions

At the moment I am using this code to inquire google maps for directions from an address to another one, then I simply draw it on a mapview from its GeometryCollection. But yet this isn't enough I need also to extract the total expected duration from the kml. can someone give a little sample code to help me? thanks
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr=");//from
urlString.append( Double.toString((double)src.getLatitudeE6()/1.0E6 ));
urlString.append(",");
urlString.append( Double.toString((double)src.getLongitudeE6()/1.0E6 ));
urlString.append("&daddr=");//to
urlString.append( Double.toString((double)dest.getLatitudeE6()/1.0E6 ));
urlString.append(",");
urlString.append( Double.toString((double)dest.getLongitudeE6()/1.0E6 ));
urlString.append("&ie=UTF8&0&om=0&output=kml");
//Log.d("xxx","URL="+urlString.toString());
// get the kml (XML) doc. And parse it to get the coordinates(direction route).
Document doc = null;
HttpURLConnection urlConnection= null;
URL url = null;
try
{
url = new URL(urlString.toString());
urlConnection=(HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
dbf = DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
doc = db.parse(urlConnection.getInputStream());
if(doc.getElementsByTagName("GeometryCollection").getLength()>0)
{
//String path = doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getNodeName();
String path = doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getFirstChild().getNodeValue() ;
//Log.d("xxx","path="+ path);
String[] pairs = path.split(" ");
String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude lngLat[1]=latitude lngLat[2]=height
// src
GeoPoint startGP = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));
mMapView01.getOverlays().add(new MyOverLay(startGP,startGP,1));
GeoPoint gp1;
GeoPoint gp2 = startGP;
for(int i=1;i<pairs.length;i++) // the last one would be crash
{
lngLat = pairs[i].split(",");
gp1 = gp2;
// watch out! For GeoPoint, first:latitude, second:longitude
gp2 = new GeoPoint((int)(Double.parseDouble(lngLat[1])*1E6),(int)(Double.parseDouble(lngLat[0])*1E6));
mMapView01.getOverlays().add(new MyOverLay(gp1,gp2,2,color));
//Log.d("xxx","pair:" + pairs[i]);
}
mMapView01.getOverlays().add(new MyOverLay(dest,dest, 3)); // use the default color
}
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}catch (SAXException e){
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
}
Use the new Directions api. The duration is returned in the response and no more parsing of KML, which I think breaks the Google maps license terms anyways.
Update. Ok use the JSON output, with it parsing is built into Android.
Ex url
Response is
{
"status": "OK",
"routes": [ {
"summary": "I-40 W",
"legs": [ {
"steps": [ {
"travel_mode": "DRIVING",
"start_location": {
"lat": 41.8507300,
"lng": -87.6512600
},
"end_location": {
"lat": 41.8525800,
"lng": -87.6514100
},
"polyline": {
"points": "a~l~Fjk~uOwHJy#P",
"levels": "B?B"
},
"duration": {
"value": 19,
"text": "1 min"
},
"html_instructions": "Head \u003cb\u003enorth\u003c/b\u003e on \u003cb\u003eS Morgan St\u003c/b\u003e toward \u003cb\u003eW Cermak Rd\u003c/b\u003e",
"distance": {
"value": 207,
"text": "0.1 mi"
}
},
...
... additional steps of this leg
...
... additional legs of this route
"duration": {
"value": 74384,
"text": "20 hours 40 mins"
},
"distance": {
"value": 2137146,
"text": "1,328 mi"
},
"start_location": {
"lat": 35.4675602,
"lng": -97.5164276
},
"end_location": {
"lat": 34.0522342,
"lng": -118.2436849
},
"start_address": "Oklahoma City, OK, USA",
"end_address": "Los Angeles, CA, USA"
} ],
"copyrights": "Map data ©2010 Google, Sanborn",
"overview_polyline": {
"points": "a~l~Fjk~uOnzh#vlbBtc~#tsE`vnApw{A`dw#~w\\|tNtqf#l{Yd_Fblh#rxo#b}#xxSfytAblk#xxaBeJxlcBb~t#zbh#jc|Bx}C`rv#rw|#rlhA~dVzeo#vrSnc}Axf]fjz#xfFbw~#dz{A~d{A|zOxbrBbdUvpo#`cFp~xBc`Hk#nurDznmFfwMbwz#bbl#lq~#loPpxq#bw_#v|{CbtY~jGqeMb{iF|n\\~mbDzeVh_Wr|Efc\\x`Ij{kE}mAb~uF{cNd}xBjp]fulBiwJpgg#|kHntyArpb#bijCk_Kv~eGyqTj_|#`uV`k|DcsNdwxAott#r}q#_gc#nu`CnvHx`k#dse#j|p#zpiAp|gEicy#`omFvaErfo#igQxnlApqGze~AsyRzrjAb__#ftyB}pIlo_BflmA~yQftNboWzoAlzp#mz`#|}_#fda#jakEitAn{fB_a]lexClshBtmqAdmY_hLxiZd~XtaBndgC",
"levels": "BBBAAAAABAABAAAAAABBAAABBAAAABBAAABABAAABABBAABAABAAAABABABABBABAABB"
},
"warnings": [ ],
"waypoint_order": [ 0, 1 ]
} ]
}
Let's say you used the standard http client libraries and now have the response in a String.
JSONObject jsonObject = new JSONObject(response); // parse response into json object
JSONObject routeObject = jsonObject.getJSONObject("route"); // pull out the "route" object
JSONObject durationObject = jsonObject.getJSONObject("duration"); // pull out the "duration" object
String duration = durationObject.getString("text"); //this should be the duration text value (20 hours 40 mins)
You will have to wrap all that in a try-catch block to catch the JSONExceptions.

Categories

Resources