JSONArray in JSONObject, how to retrieve? - android

I have a JSONObject with 2 JSONArrays with JSONObjects. I'm wondering how do I access the JSONObjects in the JSONArray located in the JSONObject?(JSON inception!).
Clarify(even I get confused of writing it this)
I first get an JSONObject
This object contains 2 JSONArrays
These 2 arrays have X and Y amounts of JSONObjects.
How I reach the "Deepest" JSONObjects? How do I "unfold" the first JSONObject to get the first 2 JSONArrays?
Any hints or tricks to share?

Yuo could use something like this new JSONObject(json).getJSONArray(arrayname1).getJSONObject(positionx).
Here json is the JSON response string. arrayname1 is the name of your first array. and poitionx is any position fromX JSONObjects.
Similarly you could use new JSONObject(json).getJSONArray(arrayname2).getJSONObject(positiony) for the other one.

Any hints or tricks to share?
Yes, use a JSON library like GSON from Google.
Here is a reference on using it. http://java.sg/parsing-a-json-string-into-an-object-with-gson-easily/
Good luck!

Here is the example.
Suppose We have an JSONObject "Space" having two arrays: one and two.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("url");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
JSONObject json=new JSONObject(result);
JSONObject resp= (JSONObject) json.get("response");
JSONObject Space=resp.getJSONObject("Space");
JSONArray One=Space.getJSONArray("one");
int Length=One.length();
for(int i=0;i<length;i++)
{
JSONObject item = (JSONObject) items.get(j);
String x=item.getString("x);
String y=item.getString("y");
System.out.println("x = "+x+" , y = "+y);
}
And in the same manner you can work with second array.

Related

How can i get data from server?

after running the url i am getting data in the following form
[
{
"user_name": "riz",
"gems_available": "10",
"free_gems": "110"
},
{
"match_name": "ausvsind",
"Match_start_time": "2016-03-27 19:00:56",
"season_name": "Mid-Season"
}
]
now i want to get user_name and all the data but unable to do..i am getting this data in the result after running my app but unable to fetch.below i have my java code.please help me where i am wrong.
JSONObject jsonObj = new JSONObject();
jsonObj.put("user_id", "abc#hotmail.com");
jsonArray = new JSONArray();
jsonArray.put(jsonObj);
final HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(USER_URL);
String str = jsonArray.toString().replace("[", "");
String str1 = str.replace("]", "");
httppost.setEntity(new StringEntity(str1.toString()));
resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();
result = EntityUtils.toString(ent);
jsonArray1.put(result);
jsobj = new JSONObject(result);
us1 = jsobj.getString(TAG_USER_NAME);
us2 = jsobj.getString(TAG_GEMS_AVAILABLE);
us3 = jsobj.getString(TAG_GEMS_FREE);
Have a look at Retrofit : it helps you parse JSON into a java POJO automagically and will help you avoid non-differential boilerplate
https://github.com/square/retrofit
When I have to get data from a Json, I always you serialization.
Have a Look at GSON. With it, you have to create model Objects that match the json architecture. After it, you can access all your json attributes easily.
There is another, better way to do this.
Use modern libraries for API calls like Retrofit 2.0 with GSON.
Add Retrofit 2.0 to your project
Read: https://github.com/square/retrofit
Create POJO Object from your JSON
http://www.jsonschema2pojo.org/
select Source type > JSON
select Annotation style > GSON
Create API service interface
Step by step: http://square.github.io/retrofit/
Why are you removing the "[" and "]" characters? Those are part of the JSONArray? If you did not want them there, use a JSONObject instead.
I did not test this, so it will have some issues. Conceptually this should work for you:
JSONObject jsonObj = new JSONObject();
jsonObj.put("user_id", "abc#hotmail.com");
final HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(USER_URL);
httppost.setEntity(new StringEntity(jsonObj.toString()));
resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();
result = EntityUtils.toString(ent);
JSONArray jsonArr = new JSONArray(result);
for (int i = 0; i < jsonArr.length(); i++)
{
JSONObject jobj = jsonArr.getJSONObject(i);
if (jobj.has("user_name"))
{
us1 = jobj.getString("user_name");
}
if (jobj.has("gems_available"))
{
us2 = jobj.getString("gems_available");
}
if (jobj.has("free_gems"))
{
us3 = jobj.getString("free_gems");
}
}

How to parse a specific response of a RESTful WS using JSON

I am learning how to parse a response from a restful web service It is supposed to retreive a JSON string so I can parse it, I am using the apache libs in android. Following some questions here in StackOverflow I do the following:
HttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(URL);
ResponseHandler<String> handler = new BasicResponseHandler();
try{
result = httpClient.execute(request, handler); ...
with that I can retreive the result of the WS as this:
"[{\"CodigoRTA\":\"0\",\"MensajeRTA\":\"\",\"Respuesta\":\"[{\\"codigo\\":\\"05\\",\\"nombre\\":\\"ANTIOQUIA\\"},{\\"codigo\\":\\"76\\",\\"nombre\\":\\"VALLE DEL CAUCA\\"}]\"}]"
the thing is that I am trying to parse it with JSONObject and JSONArray without success; When I try to use the JSONObject the errorhandler says that it cannot convert the string into JSONObject, so I look up for an answer or a similar problem and found that if the result starts with [] square brackets represents starting of an JSONArray node and curly bracket {} represents JSONObject, so I try to use this code:
//JSONObject jsonObject = new JSONObject(result);
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
codeDepartment[i] = json_data.getInt("codigo");
NameDepartment[i] = json_data.getString("nombre");
}
without success either, it now says that "it cannot convert String into JSONArray. So any idea of what can I use? any help would be really appreciated.
Well, it seems that the server response is similar to Json response, the thing is all of the \ that it contains. One thing you could do is to replace or remove 1 of the \ backslash and then try to asign the new value to the JSONArray. Something like this:
result = httpClient.execute(request, handler);
result = result.replace("here the info you want to replace", "here with new values to replace with ");
JSONArray jArray = new JSONArray(result);
hope it help you.

java.lang.Long cannot be converted to JSONArray

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
"http://gateway.ceylonlinux.com/hayleys2/services/getUserStokDetail?token=40da9b9ed74f672c3871d76a2c87857b&timestamp=0");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpClient.execute(httpPost, responseHandler);
JSONObject posts = new JSONObject(responseBody);
JSONArray jArray = posts.getJSONArray("timestamp");
Log.i("Tag", jArray.toString());
I tried above code to retrieve data from server but when i try that i get following error
12-06 11:12:27.539: W/System.err(4870): org.json.JSONException: Value 1386308549000 at timestamp of type java.lang.Long cannot be converted to JSONArray
timestamp is value instead of JSONArray.stock is JSONArray. get both value as:
JSONArray jArray = posts.getJSONArray("stock"); /// get stock JSONArray
Log.i("Tag", jArray.toString());
long timestamp=posts.getLong("timestamp"); /// get timestamp
Replace this line
JSONArray jArray = posts.getJSONArray("timestamp");
With this one :
long mTimeStamp = posts.getLong("timestamp");
Because in your JSON String timestamp is an long value not an array
In your JSON String stock is an array so you can get stock by using this
JSONArray jArray = posts.getJSONArray("stock");
check your Json string whether it has jsonArray named timestamp or it have only a long variable named timestamp. you can check this link for json structure also.

How to get the values from webservice in android

I wrote a web service in asp.net and called it in my android application using a JSON webservice. This is my code to call the web service from android
httpPost request = new HttpPost(url);
request.setHeader("Content-Type","application/json");
request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
HttpResponse response = client.execute(request);
String jsonResponse = EntityUtils.toString(response.getEntity());
JSONObject jobj=new JSONObject(jsonResponse);
JSONArray jsonArray=jobj.getJSONArray("d");
result=(String) jobj.getString("d")
I need to get each value from the result. How is it possible?
My web service result is:
{"d":"{\"Password\":33,\"Userid\":\"343\",\"Username\":fgfg}"}
Just remove below line
JSONArray jsonArray=jobj.getJSONArray("d");
because you don't ve any JSONArray in your response then d is the only object then remaining all values are in string because all in double cotes("")...
First of all,form your json like below:
{"d":{\"Password\":33,\"Userid\":\"343\",\"Username\":fgfg}}
So,that you can get,
JSONObject jobj=new JSONObject(jsonResponse);
JSONObject jsonObj=jobj.getJSONObject("d");
now you can get the value for Username like:
String Username = jsonObj.getString("Username");
Similarly you can get the other values also..
Just do
resultPassword = jsonArray.getString("Password");
That should work. Obviously change "Password" for each ID of the data you want to get.

JSON parsing in android: No value for x error

Here is the code I'm using inside my AsyncTask
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
char[] buffer = new char[(int)responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
result = new String(buffer);
return result;
This returns a string result and in my onPostExecute method I try to parse that input string:
JSONObject vehicle = new JSONObject(new String(result));
makeEdit.setText(vehicle.getString("make"));
plateEdit.setText(vehicle.getString("plate"));
modelEdit.setText(vehicle.getString("model"));
yearEdit.setText(vehicle.getString("year"));
As soon as it reaches makeEdit.setText it throws an error - no value for make. I'm still very new to android, so don't send death threats if there was some obvious error. The input text is the following JSON string:
{"GetJSONObjectResult":{"make":"Ford","model":"Focus","plate":"XXO123GP","year":2006}}
No value for x error message is pretty common when dealing with JSON. This usually resulted by overlooked code.
usually, when dong JSON, I try to see the human readable structure first. For that, I usually use JSONViewer.
In your case, the structure is something like this:
You see that make is within another object called GetJSONObjectResult. Therefore, to get it, you must first get the container object first:
JSONObject vehicle = ((JSONObject)new JSONObject(result)).getJSONObject("GetJSONObjectResult");
//a more easy to read
JSONObject container = new JSONObject(result);
JSONObject vehicle = container.getJSONObject("GetJSONObjectResult");
and finally use the object to get make:
makeEdit.setText(vehicle.getString("make"));
plateEdit.setText(vehicle.getString("plate"));
modelEdit.setText(vehicle.getString("model"));
yearEdit.setText(vehicle.getString("year"));
Your JSON Object contains itself a JSONObject. To acces to your data, you have to do like this:
vehicle.getJSONObject("GetJSONObjectResult").getString("make");

Categories

Resources