Populating JSON array with JSON objects - android

In the below code I am trying to populate the JSON array with JSON objects (book, and camera).
[ {
"camera":{
"picture":"http:\/\/img7.flixcart.com\/image\-imacyb5emj5yztet.jpeg",
"model":"Lumix DMC-FP3 Point & Shoot",
"make":"Panasonic",
"price":5830
}
},
{
"camera":{
"picture":"http:\/\/sp.sony-europe.com\/da.jpeg",
"model":"Digital Still Camera - H Series - DSC-HX200V",
"make":"Sony",
"price":510
}
},
{
"book":{
"description":"What is self, and how can a",
"authors":"Douglas R Hofstadter",
"price":650,
"id":40724766,
"title":"G\u00f6del, Escher, Bach: an Eternal Golden Braid"
}
},
{
"camera":{
"picture":"http:\/\/www.usa.canon.com\/60d_586x186.gif",
"model":"Digital SLR Camera EOS 60D",
"make":"Canon",
"price":999
}
},
{
"book":{
"description":"Tgdfgf fgfg ",
"authors":"Harold Abelson and Gerald Jay Sussman with Julie Sussman",
"price":469,
"id":51087,
"title":"Structure and Interpretation of Computer Programs"
}
},
]
public void getDetalFromServer() {
// TODO Auto-generated method stub
String URL="xyz.php";
HttpClient client= new DefaultHttpClient();
HttpPost post=new HttpPost(URL);
try {
HttpResponse response =client.execute(post);
HttpEntity getResEntity=response.getEntity();
String result="";
if(getResEntity!=null){
result=EntityUtils.toString(getResEntity);
System.out.println("result from server: "+result);
bookDescription=new ArrayList<String>();
bookAuthors=new ArrayList<String>();
bookPrice=new ArrayList<String>();
bookID=new ArrayList<String>();
bookTitle=new ArrayList<String>();
responseArray=new JSONArray(result);
for(int i=0;i<responseArray.length();i++){
JSONObject bookObject=(JSONObject) responseArray.getJSONObject(i);
bookDescription.add(bookObject.get("description").toString());
bookAuthors.add(bookObject.get("authors").toString()); bookPrice.add(bookObject.get("price").toString());
bookID.add(bookObject.get("id").toString()); bookTitle.add(bookObject.get("title").toString());
}
}
} catch (Exception e) {
// TODO: handle exception
}
}
Using this code I am able to just get the first object of the response. Now I am just trying to parse Music object from the response.

responseArray=new JSONArray(result);
JSONObject bookObject=null;
JSONObject json_user1=null;
JSONObject json_user2=null;
for(int i=0;i<responseArray.length();i++){
bookObject= responseArray.getJSONObject(i);
if (bookObject.has("book")){
json_user1 = bookObject.getJSONObject("book");
bookDescription.add(json_user1.getString("description").toString());
bookAuthors.add(json_user1.getString("authors").toString());
}
else if(bookObject.has("camera")){
json_user2 = bookObject.getJSONObject("camera");
/** Add Camera data in the lists here same as done for book */
}
}
Try this.... Inside your json array you have put json objects. so you need to retrieve json objects like book and camera from the array first and then from book object you can get the description and all... :)

Related

Troubles with parsing JSON for android

I'm working on parsing some JSON in my android application, this is the code I started off with:
JSONObject jsonObject = **new JSONObject(result);**
int receivedCount = **jsonObject.getInt("CurrentCount");**
However this is causing it to error (The code that would error is surrounded with asterisks) in Android Studio, I tried using the suggestion feature which asked me if I want "Surround with try/catch" which would cause the app to crash when it launched.
This is the suggested code:
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(result);
} catch (JSONException e) {
e.printStackTrace();
}
int receivedCount = 0;
try {
receivedCount = jsonObject.getInt("CurrentCount");
} catch (JSONException e) {
e.printStackTrace();
}
This is the JSON I'm trying to pass:
[{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}]
Thanks in advance!
J_Dadh I think first of all you should look through the documentation on how to use Json Parser which you can find in the following Link https://www.tutorialspoint.com/android/android_json_parser.htm
EXAMPLE JSON
{
"sys":
{
"country":"GB",
"sunrise":1381107633,
"sunset":1381149604
},
"weather":[
{
"id":711,
"main":"Smoke",
"description":"smoke",
"icon":"50n"
}
],
"main":
{
"temp":304.15,
"pressure":1009,
}
}
String YourJsonObject = "JsonString"
JSONObject jsonObj = new JSONObject(YourJsonObject);
JSONArray weather = jsonObj.getJSONArray("weather");
for (int i = 0; i < weather.length(); i++) {
JSONObject c = weather.getJSONObject(i);
String id = c.getString("id");
String main= c.getString("main");
String description= c.getString("description");
}
as you pasted your JSON you are using [{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}]
-If we analyze this JSON,This JSON contains a JSON ARRAY [{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}]
having 3 JSON Objects{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}
-But when you are going to parse this JSON, you are accepting it as jsonObject = new JSONObject(result),but you should accept it asJSONArray jsonArray=new JSONArray(result);
and then you iterate a loop(e.g,for loop) on this jsonArray,accepting JSONObjects 1 by 1,then getting the values from the each JSONObject 1 by 1.
-1 more mistake in your JSON is that you are sending the strings as "5" but accepting it as getInt() that's not fair,you should send int to accept it as intas 5 (without double qoutes)
So you final JSON and code like this(as below)
JSON
[{"CurrentCount":5},{"CurrentCount":0},{"CurrentCount":1002}]
Code to Use this JSON
JSONOArray jsonArray = null;
try{
jsonArray = new JSONArray(result);
for(int i=0;i<jsonArray.length;i++){
JSONObject jsonObject=jsonArray[i];
receivedCount=jsonObject.getInt("CurrentCount");
}
}catch(JSONException e) {
e.printStackTrace();
}

Json String created in Wrong Format

I have to send request body in Http request in below format:
{
"flag":false,
"Ids":["xyz","abc"]
}
I was trying like:
LinkedHashMap<String, Object> requestParamsMap = new LinkedHashMap<String, Object>();
requestParamsMap.put("flag",false);
ArrayList<String> IdList = new ArrayList<>();
IdList.add("xyz");
IdList.add("abc");
requestParamsMap.put("Ids", IdList.toString());
And then I was converting requestParamsMap to json string. But I am not getting request body in desired format.
I want to create a generalized method which can return me data in this type of format, so that I can use it throughout application.
Any help would be appreciated.. !!!
Do something like this:
JSONObject object=new JSONObject();
try {
object.put("flag","xyz");
JSONArray array=new JSONArray();
array.put("xyz");
array.put("abc");
object.put("Ids",array);
//added a log to see the output
Log.e("output",object.toString());
} catch (JSONException e) {
e.printStackTrace();
}
object.toString() should contain exactly the json you want in string format. You can use a loop to populate the contents of the jsonArray or JSONObject depending on the number of items you have
Its not that though at all, output you want is JSONArray inside JSONObject and JSONObject inside another JSONObject. So, you can create them seperately and then can put in together. as below.
CODE
try {
JSONObject parent = new JSONObject();
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
jsonArray.put("lv1");
jsonArray.put("lv2");
jsonObject.put("mk1", "mv1");
jsonObject.put("mk2", jsonArray);
parent.put("root", jsonObject);
Log.d("output", parent.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
OUTPUT
{
"root": {
"mk1": "mv1",
"mk2": [
"lv1",
"lv2"
]
}
}

Trying to convert JSON data to a JSON array in Android Studio

Hello im trying to convert some JSON data into an array, I have dont it this way before but without objects
http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/1.0_day.geojson
Here is the code that gets the data and trys to convert it
public JSONArray getQaukes()
{
String url = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/1.0_day.geojson";
// Get HttpResponse Object from url.
// Get HttpEntity from Http Response Object
HttpEntity httpEntity = null;
try
{
DefaultHttpClient httpClient = new DefaultHttpClient(); // Default HttpClient
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
} catch (ClientProtocolException e) {
// Signals error in http protocol
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Convert HttpEntity into JSON Array
JSONArray jsonArray = null;
if (httpEntity != null) {
try {
String entityResponse = EntityUtils.toString(httpEntity);
Log.d("Entity Response : ", entityResponse);
jsonArray = new JSONArray(entityResponse);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return jsonArray;
}
This is what i get
http://pastebin.com/HVnx3gsq
Anyone know how I could find the correct way to do this?
Thanks
The result is a JSONObject not JSONArray.
Instead of JSONArray jsonArray = new JSONArray(entityResponse);
You should have JSONObject jObj = new JSONObject(entityResponse);
Edit: As an example, if you were to extract "features" Array, then you should do it like that:
//First of all - create JSON Object which you are going to parse (deserialize JSON string)
JSONObject jsonObj = new JSONObject(entityResponse);
// Extract JSON array from Object
JSONArray jsonArray = jsonObj.getJSONArray("features");
Your JSON string has many different elements, that is why you need to create JSON object, then extract arrays from it and so on. Until the very last token.
"type":"FeatureCollection",
"metadata":{
"generated":1452461493000,
"url":"http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/1.0_day.geojson",
"title":"USGS Magnitude 1.0+ Earthquakes, Past Day",
"status":200,
"api":"1.1.0",
"count":128
},
"features":[
{
"type":"Feature",
"properties":{
"mag":2.07,
"place":"28km S of Gardnerville Ranchos, Nevada",
"time":1452460963440,
"updated":1452461071893,
"tz":-480,
"url":"http://earthquake.usgs.gov/earthquakes/eventpage/nc72578341",
"detail":"http://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/nc72578341.geojson",
"felt":null,
"cdi":null,
"mmi":null,
"alert":null,
"status":"automatic",
"tsunami":0,
"sig":66,
"net":"nc",
"code":"72578341",
"ids":",nn00526227,nc72578341,",
"sources":",nn,nc,",
"types":",general-link,general-link,geoserve,nearby-cities,origin,phase-data,",
"nst":8,
"dmin":0.06765,
"rms":0.11,
"gap":197,
"magType":"md",
"type":"earthquake",
"title":"M 2.1 - 28km S of Gardnerville Ranchos, Nevada"
},
"geometry":{
"type":"Point",
"coordinates":[
-119.751503,
38.6351662,
-1.8
]
},
"id":"nc72578341"
},
{
"type":"Feature",
"properties":{
"mag":2.3,
In the extract above you have: "type" - JSON value, "metadata" - JSON Object, "features" - JSON Array and so on.
I recommend you looking into JSON syntax, so then you will be able to understand how to parse the data: http://www.w3schools.com/json/json_syntax.asp

Trouble with JSON exception - Android

I am having trouble figuring out why i'm getting a JSON exception while I am parsing my JSON object. I am getting(Http GET) the JASON from a URL. Here is all the relevant code, let me know if you need to see any more of the code
The doInBackground Async method:
#Override
protected Void doInBackground(Void... arg0)
{
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(URL,ServiceHandler.GET);
Log.w("Rakshak", "the jaon String is:"+jsonStr);// this prints the JASON in the log and it looks fine
// I am not pasting it in coz it is HUGE
if (jsonStr != null)
{
try {
JSONObject jsonObj = new JSONObject(jsonStr);
Log.w("Rakshak", "in the try before the JASON");
// Getting JSON Array node
kingtide = jsonObj.getJSONArray("JASON");
// looping through All Kingtide events
for (int i = 0; i < kingtide.length(); i++)
{
JSONObject k = kingtide.getJSONObject(i);
String date = "Date Range:"+k.getString(KEY_DATE);
String lat = k.getString(KEY_LAT);
String lng = k.getString(KEY_LNG);
String loc = "Location of the Kingtide:"+k.getString(KEY_LOC)+", "+k.getString(KEY_STATE);
String temp_Time = k.getString(KEY_TIME);
String[] time_parts = temp_Time.split("T");
String time = "Kingtide at:"+time_parts[1]+" "+getYear(time_parts[0]);
// tmp hashmap for single kingtide event
HashMap<String, String> kt = new HashMap<String, String>();
// adding each child node to HashMap key => value
kt.put(KEY_DATE, date);
kt.put(KEY_LAT, lat);
kt.put(KEY_LNG, lng);
kt.put(KEY_LOC, loc);
kt.put(KEY_TIME, time);
Log.w("Rakshak", KEY_DATE+KEY_LAT+KEY_LNG+KEY_LOC+KEY_TIME);
// adding the kingtide to the kingtide hash map. this will be used to fill up the list view
kingTideList.add(kt);
}
} catch (JSONException e) {
Log.e("Rakshak", "JSONException "+e.getMessage()); // this prints "JSONException Value [{"Latitude":-19.9078861,"Location":"Abbot....." and the rest of the JASON(all of it)
}
}
else
Log.w("Rakshak", "JASON string is null");
return null;
}
the Service handler class:
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
Log.e("Rakshak", "UnsupportedEncodingException "+e.getMessage());
} catch (ClientProtocolException e) {
Log.e("Rakshak", "ClientProtocolException "+e.getMessage());
} catch (IOException e) {
Log.e("Rakshak", "IOException "+e.getMessage());
}
Log.w("Rakshak", "In the service handeler: this is a test");
return response;
}
}
Part of the stacktrace:
03-14 10:09:56.861: E/Rakshak(7037): JSONException Value [{"Latitude":-19.9078861,"Location":"Abbot Point","Longitude":148.08467259999998,"DateRange":"1–3 January 2014","HighTideOccurs":"2014-01-02T09:47:00","State":"QLD"},{"Latitude":-27.477819,"Location":"Brisbane
The URL for the JASON file is "http://witnesskingtides.azurewebsites.net/api/kingtides"
NOTE: I know it looks like a XML file but it is JASON . Just run it through a validator/viewer and see for your self if you want.
My question in why am I getting a JASON exception and how do I fix it.
The Response you are getting is XML response and you are trying to parse it as JSON.
Refer this tutorial on XML parsing
When getting the contents, I get this back (part of it):
[
{
"Location": "Abbot Point",
"State": "QLD",
"HighTideOccurs": "2014-01-02T09:47:00",
"DateRange": "1–3 January 2014",
"Latitude": -19.9078861,
"Longitude": 148.08467259999998
},
{
"Location": "Brisbane Bar",
"State": "QLD",
"HighTideOccurs": "2014-01-02T10:16:00",
"DateRange": "1–3 January 2014",
"Latitude": -27.477819,
"Longitude": 153.01889119999998
},
...
]
This means that your object is already an array. Try to change this in your code:
//JSONObject jsonObj = new JSONObject(jsonStr);
Log.w("Rakshak", "in the try before the JASON");
// Getting JSON Array node
kingtide = new JSONArray(jsonStr);
since the returned jsonStr is already an array (and not an object with an array-attribute called "JASON").
Confirmed that the service is in fact returning a JSON response (you can check this in a tool like Fiddler). The default response from the API is JSON. The reason you are seeing XML by clicking the link provided in the question is because the browser is requesting a content type of application/xml, so that is what the browser shall receive.
I don't know the answer to your actual problem though, as the JSON seems to validate in everything I've tried. Maybe an incompatibility with the Android parser?
I'd suggest trying a different parser in your Android app to parse the response from the server. I've used Gson before which was easy to set up and use.
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
The service returns an array of objects so instead of
JSONObject jsonObj = new JSONObject(jsonStr);
use
JSONArray jsonArray = new JSONArray(jsonStr);
and continue from there.
Update: Disregard my answer below...
Not to burst your repeated notion of the fact that it is JSON, it is not.
The response that your code gets back is plain XML.
However,
The resource you are requesting ( http://witnesskingtides.azurewebsites.net/api/kingtides ) supports both XML formatted responses and JSON formatted responses. It probably all has to do with the Accept headers that are missing from your request in your code or are set to application/xml or text/xml or something similar in your ServiceHandler.
When your code gets the response of the server, the server does not find an Accept header and returns XML format.
When the JSON validator sites, that you mention, request the same URL, they likely add an Accept header that tells the server to return the response in JSON format.
I'm not sure how the ServiceHandler class works, but when you create a GET request you should add the HTTP Header with name Accept and value application/json and then issue the request. You now will get JSON back instead of XML.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html

JsonArray parsing

I'm parsing a json file but i get this message: org.json.JSONException: End of input at character 0 of
the contetnn of the file is:
Are you sure there is not an empty line at the end of the file? Like this:
[
{
code: "UNLC",
cours_jour: "40 020",
variation: "0.00"
},
{
code: "UNXC",
cours_jour: "7 450",
variation: "0.00"
}
]
<-- Empty line here!
Your JSON Object fields need to be encapsulated by quotes
IE
{
"code": "BOAC",
"cours_jour": "29 000",
"variation": "-1.69"
}
How was the JSON file generated?
--Edit
You can use the below code to download the page to a string and then convert it to a JSONArray and then pull each JSONObject. You cannot run any web requests on the main thread so either extend a new asynctask or thread or runnable to perform the below
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost("http://www.impaxis-securities.com/securities/cours-actions/cours.json");
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response;
try {
response = httpclient.execute(httpost, responseHandler);
JSONArray arr = new JSONArray(response);
int arrLength = arr.length();
if(arrLength > 0)
{
for(int i = 0; i < arrLength; i++)
{
JSONObject item = arr.getJSONObject(i);
String code = item.getString("code");
String cours_jour = item.getString("cours_jour");
String variation = item.getString("variation");
//Either insert to a DB or add to an array list and return it
}
}
}
catch (ClientProtocolException e) {
//Issue with web server
}
catch (IOException e) {
//Issue with request
}
catch (JSONException e) {
//ISSUE Parsing JSON from site
}
---Edit
I tested the code and it looks like there is a bug with the JSON plugin/REST service
http://drupal.org/node/1433436

Categories

Resources