parse json array in android - java

I need a help... I have a php file which returns me two json Arrays which are as follows:
[{ "id":"1",
"item":"hammers",
"aisle":"20"
}
{ "id":"1",
"item":"hammers",
"aisle":"20"
}]
[{ "id":"1",
"itemFound":"Your item #item",
"ThankYou":"and Thank You for using Txtcore!"
}]
Now, I want to get the second array items in Android. I have the following code now which is like :
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
items.add(jsonObject.getString("item"));
aisles.add(""+jsonObject.getString("item");
}
But obviously, that returns me the objects from the first array. I want to get the Objects from the second array. Any suggestions.

Your JSON is not valid but u can get your element as follows. It is a solution from many(just a worlaround).
String str = "YOUR_JSON_RESPONSE";
String array[] = str.split("\\[\\{");//
try {
JSONArray jsonArray=new JSONArray("[{" + array[2]));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

I guess you'll have to do some dirty coding because the data return by the PHP page is not well formed JSON.
You could try to transform the JSON data to:
{ "data" : [ <array_1>, <array_2> ]} And then use the JSON parser. A simple replacement with a regexp could be fine.
result.replaceAll("\\]\\s*\\[", "], [");
StringBuffer buffer=new StringBuffer(result);
buffer.insert(0,"{ \"data\": ");
buffer.append(" }");
JSONObject jsonObject = new JSONObject(buffer.toString());
JSONArray secondArray= jsonObject.getJSONArray("data").getJSONArray(1);
The creation of a valid JSON string can be done in one step with the appropriate regexp. Hope some one with more time can post it here.

Related

How to access JSON value?

Very new to JSON, this is probably very simple but I'm not sure how to access the "coordinates" in this JSON I know how to go from resourceSets to resources but get stuck at "point":
{
"resourceSets":[
{
"estimatedTotal":1,
"resources":[
{
"__type":"Location:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1",
"bbox":[
51.3223903,
-0.2634519,
51.3246386,
-0.2598541
],
"name":"name",
"point":{
"type":"Point",
"coordinates":[
51.3235145,
-0.261653
]
}
}
]
}
]
}
My code so far:
JSONParser parser = new JSONParser();
JSONObject jObj = (JSONObject)parser.parse(result);
JSONArray jsonArray = (JSONArray)jObj.get("resourceSets");
for (int i = 0; i < jsonArray.size(); i ++) {
JSONObject jObjResourceSets = (JSONObject)jsonArray.get(i);
JSONArray jsonArray2 = (JSONArray)jObjResourceSets.get("resources");
System.out.println("Coords" + jObjResourceSets.get("point"));
}
Lets analyse what you're doing (and need to be doing), step by step, in order to get the "coordinates".
First of all, JSON is a great language to transfer static data. It works like a dictionary, where you have a key and the respective value. The key should always be a String, but the value can be a String, an int/double or even an array of other JSON objects. That's what you have.
For instance, "estimatedTotal" is an element (JSONObject) from the "resourceSet" array (JSONArray).
JSONArray jsonArray = (JSONArray)jObj.get("resourceSets");
What you're saying here is straight forward: from your overall JSONObject - jObj - you want to extract the array with key "resourceSets".
Now you have direct access to "resourceSets" array elements: "estimatedTotal", "resources", etc. So, by applying the same logic, in order to access "coordinates" we need to access the "resources" array. And by that I mean to create a JSONArray object like we did before.
JSONArray jsonResourcesArray = (JSONArray)jObjResourceSets.get("resources");
I hope it's clear what's the content of jsonResourcesArray here. It's the JSON array of "__type", "bbox", "name", "point", (...). The Coordinates howevere are inside "point" JSON object. How do we access it?
JSONObject jsonPointObject = (JSONObject) jsonResourcesArray.get("point");
And you know by know that "jsonPointObject" has as its values the following JSON objects: "type" and "coordinates". Coordinates is an array of values, so do we have to use JSONArray or JSONObject?
JSONArray jsonCoordinatesArray = (JSONArray) jsonPointObject.get("coordinates");
From which we mean: from the jsonPointObject we want to extract the array that has key "coordinates". Now your array is a JSONArray with values of jsonCoordinatesArray.get(0) and jsonCoordinatesArray.get(0).
Now you have, not only the code to get those values, but the understanding of how JSON works and how Java interacts with it so you can solve any Json problem from now on.
Normally this code works for the given JSON object. However I'll put the tested formatted JSON value below the java code so you can test it as well.
Note that this code will get you all the coordinates of all the elements in your object.
public static void main(String[] args) throws Exception {
String result = getJsonString();
// Getting root object
JSONParser parser = new JSONParser();
JSONObject jObj = (JSONObject)parser.parse(result);
// Getting resourceSets Array
JSONArray jsonArray = (JSONArray)jObj.get("resourceSets");
for (int i = 0; i < jsonArray.size(); i++) {
// Getting the i object of resourceSet
JSONObject jObjResourceSets = (JSONObject) jsonArray.get(i);
// Getting resources list of the current element
JSONArray jsonArray2 = (JSONArray) jObjResourceSets.get("resources");
for (int j = 0; j < jsonArray2.size(); j++) {
// Getting the j resource of the resources array
JSONObject resource = (JSONObject) jsonArray2.get(j);
// Getting the point object of the current resource
JSONObject point = (JSONObject) resource.get("point");
// Getting the coordinates list of the point
JSONArray coordinates = (JSONArray) point.get("coordinates");
for (int k = 0; k < coordinates.size(); k++) {
System.out.println("Coordinates[" + k + "]: " + coordinates.get(k));
}
// Printing an empty line between each object's coordinates
System.out.println();
}
}
}
The tested JSON Object:
{
"resourceSets":[
{
"estimatedTotal":1,
"resources":[
{
"__type":"Location:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1",
"bbox":[
51.3223903,
-0.2634519,
51.3246386,
-0.2598541
],
"name":"name",
"point":{
"type":"Point",
"coordinates":[
51.3235145,
-0.261653
]
}
}
]
}
]
}
If it worked please mark it as the answer.
Good luck ^^
B.
You need the following piece of code to get the data.
JSONArray jsonArray2 = (JSONArray)jObjResourceSets.get("resources");
/**
* here we should note that the "resources" is only having one JSON object hence we can take it as below
* from 0th index using ((JSONObject)jsonArray2.get(0)) these piece of code and the next part is to take the point JSONObject
* from the object.
*/
JSONObject temp = (JSONObject)((JSONObject)jsonArray2.get(0)).get("point");
System.out.println("Coords"+temp.get("coordinates")); //this will give you the coordinates array
//now if you want to do further processing, traverse in the jsonArray like below
JSONArray arr= (JSONArray)temp.get("coordinates");
System.out.println("X coordinate:"+arr.get(0));
System.out.println("Y coordinate:"+arr.get(1));
For more information and further details on JSONObject and JSONArray you can go through this linkparsing-jsonarray-and-jsonobject-in-java-using-json-simple-jar
json-simple-example-read-and-write-json

how to reverse the json array after response from webservice?

I am getting response this
{
"success": 1,
"message": "some message",
"data": [
{
"comment_id": "43906",
"comp_id": "116725",
"user_id": "48322",
"agree": "0",
.....
"replies": [....]
},
{
"comment_id": "43905",
"comp_id": "116725",
"user_id": "48248",
"agree": "0",
.......
"replies": [...]
}
]
}
I am to get all response in json array like this
JSONObject js =new JSONObject(response);
routeJsonArray.=js.getJSONArray("data");
But I need to reverse all object which is inside data array .In other word when I get response and print commant_id "43906", "43905",
But I need I reverse that objects so that when I print it first give "43905","43906",
there is solution to iterate from i = routeJsonArray.length; i > 0; i-- But i don't want this.I want to store reverse array in another array ..
I try like this.
String [] routeStationString;
JSONArray localJsonArray = js.getJSONArray("data");
routeStationString = new String[localJsonArray.length()];
int k = 0;
for (int i = localJsonArray.length(); i > 0; i--) {
routeStationString[k++] = localJsonArray.getJSONObject(i);
}
System.out.println(routeStationString);
It gives error.?
My approach would be to create a Java Model representing a comment from your array and then proceed like this.
ArrayList<Comment> mList = new ArrayList<Comment>();
for(int i=0;i<routeJsonArray.length();i++){
//get the jsonobject based on the position
//retrieve its values
//create a new comment object and store it to the mList
}
Collection.reverse(mList);
You typically want to parse this array into a POJO, a model. So the idea would be to get a List<Comment> list for example and then you would be able to reverse that list through Collections.reverse(list) method.
How do you use the data from the JSON array? you still have to iterate it, plus remember the keys and everything. the most typical solution is to parse the JSON data into java objects.
JSONArray toReturn = new JSONArray();
int length = jsonArray.length()-1;
for(int i =length; i >= length;i--){
try {
toReturn.put(jsonArray.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(this, "Something wrong", Toast.LENGTH_SHORT).show();
}
}

Parse Json array without keys

I want to parse an array from Server but I can't obtain the array
Here is the jsonString Successfully got :
{
"status":"OK",
"message":"this is your start and end coordinates",
"data":"{\"start\":[\"35.778763\",\"51.427360\"],\"end\":[\"35.768779, 51.415002\"]}"
}
I want the Double Values from data arraylist:
//try/catch
Log.d(TAG, "Passes here");
JSONObject jObject = new JSONObject(jsonString);
JSONArray jData = jObject.getJSONArray("data");
Log.d(TAG, "Not PAASING HERE !!! ");
JSONArray jArrayStart = (JSONArray) jData.get(0);
JSONArray jArrayEnd = (JSONArray) jData.get(1);
latitudeStart = (Double) jArrayStart.get(0);
longtitudeStart = (Double) jArrayEnd.get(1);
latitudeEnd = (Double) jArrayEnd.get(0);
longtitudeEnd = (Double) jArrayEnd.get(1);
What you're trying to parse, is a string.
{
"status": "OK",
"message": "this is your start and end coordinates",
"data": "{\"start\":[\"35.778763\",\"51.427360\"],\"end\":[\"35.768779, 51.415002\"]}"
}
So it works like this:
//first, retrieve the data from the response JSON Object from the server
JSONObject response = new JSONObject(jsonString);
String status = response.getString("status");
String message = response.getString("message");
//Note this: "data" is a string as well, but we'll have to parse that later.
String data = response.getString("data");
//get the doubles from the arrays from the "data" component.
JSONObject dataObject = new JSONObject(data);
JSONArray start = dataObject.getJSONArray("start");
JSONArray end = dataObject.getJSONArray("end");
for (int i = 0; i < start.length(); i++) {
String value = start.getString(i);
//do something with the start String (parse to double first)
}
for (int i = 0; i < end.length(); i++) {
String value = end.getString(i);
//do something with end String (parse to double first)
}
So data is actually a String, but represents a JSONObject (which you'll have to parse), which, in its turn, contains two JSONArrays.
If data was a JSONObject instead of a String, the JSON would have looked like this:
{
"status": "OK",
"message": "this is your start and end coordinates",
"data": {
"start": [
"35.778763",
"51.427360"
],
"end": [
"35.768779", //note that in your example, this quote is missing (first quote on next line too)
"51.415002"
]
}
}
The value of data is not a JSONArray its JSONObject
Explanation
JSONObject will be surrounded by {}
JSONArray will be surrounded by []
data is not an array, it is a json object and therefore you can not access it the way you are doing.
If you want to fetch start array from json object "data" then use below
jObject.optJSONObject("data").optJSONArray("start");
same thing can be used to retrieve "end" json array.
then use optJSONObject() and/or optString() API to retrieve required value from json array.

How to convert int Array to JSON String in Android?

I expected to find this question around, but I couldn't. Maybe I'm Googling the wrong thing.
I have a primitive integer array (int[]), and I want to convert this into a String, that is "JSON-Parseable", to be converted back to the same int[].
What have I tried :
I tried this code :
// int[] image_ids_primitive = ...
JSONArray mJSONArray = new JSONArray(Arrays.asList(image_ids_primitive));
String jSONString = mJSONArray.toString();
Prefs.init(getApplicationContext());
Prefs.addStringProperty("active_project_image_ids", jSONString);
// Note: Prefs is a nice Class found in StackOverflow, that works properly.
When I printed the jSONString variable, it has the value : ["[I#40558d08"]
whereas, I expected a proper JSON String like this : {"1" : "424242" , "2":"434343"} not sure about the quotation marks, but you get the idea.
The reason I want to do this :
I want to keep track of local images (in drawable folder), so I store their id's in the int array, then I want to store this array, in the form of a JSON String, which will be later parsed by another activity. And I know I can achieve this with Intent extras. But I have to do it with SharedPreferences.
Thanks for any help!
You don't have to instantiate the JSONArray with Arrays.asList. It can take a normal primitive array.
Try JSONArray mJSONArray = new JSONArray(image_ids_primitive);
If you are using an API level below 19, one easy method would just be to loop over the int array and put them.
JSONArray mJSONArray = new JSONArray();
for(int value : image_ids_primitive)
{
mJSONArray.put(value);
}
Source: Android Developers doc
If you want a JSON array and not necessarily an object, you can use JSONArray.
Alternatively, for a quick hack:
System.out.println(java.util.Arrays.toString(new int[]{1,2,3,4,5,6,7}));
prints out
[1, 2, 3, 4, 5, 6, 7]
which is valid JSON. If you want anything more complicated than that, obviously JSONObject is your friend.
Try this way
int [] arr = {12131,234234,234234,234234,2342432};
JSONObject jsonObj = new JSONObject();
for (int i = 0; i < arr.length; i++) {
try {
jsonObj.put(""+(i+1), ""+arr[1]);
} catch (Exception e) {
}
}
System.out.println("JsonString : " + jsonObj.toString());
// If you wants the data in the format of array use JSONArray.
JSONArray jsonarray = new JSONArray();
//[1,2,1,] etc..
for (int i = 0; i < data.length; i++) {
jsonarray.put(data[i]);
}
System.out.println("Prints the Json Object data :"+jsonarray.toString());
JSONObject jsonObject=new JSONObject();
// If you want the data in key value pairs use json object.
// i.e {"1":"254"} etc..
for(int i=0;i<data.length;i++){
try {
jsonObject.put(""+i, data[i]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("Prints the Json Object data :"+jsonObject.toString());
itertate this through the int array and you will get the json string
JSONStringer img = null ;
img = new JSONStringer() .object() .key("ObjectNAme")
.object() .key("something").value(yourIntarrayAtIndex0)
.key("something").value(yourIntarrayAtIndex1) .key("something").value(yourIntarrayAtIndex2)
.key("something").value(yourIntarrayAtIndex3)
.endObject() .endObject();
String se = img.toString();
Here se is your json string in string format
This code will achieve what you are after...
int index = 0;
final int[] array = { 100, 200, 203, 4578 };
final JSONObject jsonObject = new JSONObject();
try {
for (int i : array) {
jsonObject.put(String.valueOf(index), String.valueOf(i));
index++;
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("YOUR_TAG", jsonObject.toString());
This will give you {"3" : "203", "2" : "200", "1": "100", "4": "4578"} as a string.
Not exactly sure why its not in the exact order, but sorting by a key is quite easy.

Android parse Json array of Strings

How can I parse in Android a Json array of strings and save it in a java string array ( like: xy[ ] ) ?
My Json to be parsed :
[
{
"streets": [ "street1", "street2", "street3",... ],
}
]
Later in my code I want to populated with that array a spinner item in my layout.
Everything i tried enden with only one street item listed in the spinner.
To parse
try {
JSONArray jr = new JSONArray("Your json string");
JSONObject jb = (JSONObject)jr.getJSONObject(0);
JSONArray st = jb.getJSONArray("streets");
for(int i=0;i<st.length();i++)
{
String street = st.getString(i);
Log.i("..........",""+street);
// loop and add it to array or arraylist
}
}catch(Exception e)
{
e.printStackTrace();
}
Once you parse and add it to array. Use the same to populate your spinner.
[ represents json array node
{ represents json object node
Try this..
JSONArray arr = new JSONArray(json string);
for(int i = 0; i < arr.length(); i++){
JSONObject c = arr.getJSONObject(i);
JSONArray ar_in = c.getJSONArray("streets");
for(int j = 0; j < ar_in.length(); j++){
Log.v("result--", ar_in.getString(j));
}
}
We need to make JSON object first. For example,
JSONObject jsonObject = new JSONObject(resp);
// resp is your JSON string
JSONArray arr = jsonObject.getJSONArray("results");
Log.i(LOG, "arr length = " + arr.length());
for(int i=0;i<arr.length();i++)
{...
arr may contains other JSON Objects or JSON array. How to convert the JSON depends on the String. There is a complete example with some explanation about JSON String to JSON array can be found at http://www.hemelix.com/JSONHandling

Categories

Resources