Group multiple JSONObject into JSONArray - java

Hi I Have JSON response as
[
{"sr_no":"1","stn_name":"ALUVA","arrival_time":"5:59:30","distance":"1.81"},
{"sr_no":"2","stn_name":"PULINCHUDU","arrival_time":"6:02:21","distance":"2.76"},
{"sr_no":"3","stn_name":"COMPANYPADY","arrival_time":"6:04:19","distance":"3.76"},
{"sr_no":"4","stn_name":"AMBATTUKAVU","arrival_time":"6:06:15","distance":"4.72"},
{"sr_no":"5","stn_name":"MUTTOM","arrival_time":"6:08:11","distance":"8.14"},
{"sr_no":"6","stn_name":"KALAMASSERY","arrival_time":"6:11:20","distance":"8.65"},
{"sr_no":"7","stn_name":"CUSAT","arrival_time":"6:13:40","distance":"9.15"},
{"sr_no":"8","stn_name":"PATHADIPALAM","arrival_time":"6:15:52","distance":"12.02"},
{"sr_no":"9","stn_name":"EDAPPALLY","arrival_time":"6:18:12","distance":"12.55"},
{"sr_no":"10","stn_name":"CHANGAMPUZHA PARK","arrival_time":"6:20:39","distance":"13.07"},
{"sr_no":"11","stn_name":"PALARIVATTOM","arrival_time":"6:23:10","distance":"14.43"},
{"sr_no":"1","stn_name":"ALUVA","arrival_time":"5:59:30","distance":"1.81"},
{"sr_no":"2","stn_name":"PULINCHUDU","arrival_time":"6:02:21","distance":"2.76"},
{"sr_no":"3","stn_name":"COMPANYPADY","arrival_time":"6:04:19","distance":"3.76"},
{"sr_no":"4","stn_name":"AMBATTUKAVU","arrival_time":"6:06:15","distance":"4.72"},
{"sr_no":"5","stn_name":"MUTTOM","arrival_time":"6:08:11","distance":"8.14"},
{"sr_no":"6","stn_name":"KALAMASSERY","arrival_time":"6:11:20","distance":"8.65"},
{"sr_no":"7","stn_name":"CUSAT","arrival_time":"6:13:40","distance":"9.15"},
{"sr_no":"8","stn_name":"PATHADIPALAM","arrival_time":"6:15:52","distance":"12.02"},
{"sr_no":"9","stn_name":"EDAPPALLY","arrival_time":"6:18:12","distance":"12.55"},
{"sr_no":"10","stn_name":"CHANGAMPUZHA PARK","arrival_time":"6:20:39","distance":"13.07"},
{"sr_no":"11","stn_name":"PALARIVATTOM","arrival_time":"6:23:10","distance":"14.43"}
]
Its all JSONObject but I want to group first 11 objects into array and next 11 entry into another array so response must be like:
[
[
{"sr_no":"1","stn_name":"ALUVA","arrival_time":"5:59:30","distance":"1.81"},
{"sr_no":"2","stn_name":"PULINCHUDU","arrival_time":"6:02:21","distance":"2.76"},
{"sr_no":"3","stn_name":"COMPANYPADY","arrival_time":"6:04:19","distance":"3.76"},
{"sr_no":"4","stn_name":"AMBATTUKAVU","arrival_time":"6:06:15","distance":"4.72"},{"sr_no":"5","stn_name":"MUTTOM","arrival_time":"6:08:11","distance":"8.14"},{"sr_no":"6","stn_name":"KALAMASSERY","arrival_time":"6:11:20","distance":"8.65"},{"sr_no":"7","stn_name":"CUSAT","arrival_time":"6:13:40","distance":"9.15"},{"sr_no":"8","stn_name":"PATHADIPALAM","arrival_time":"6:15:52","distance":"12.02"},{"sr_no":"9","stn_name":"EDAPPALLY","arrival_time":"6:18:12","distance":"12.55"},{"sr_no":"10","stn_name":"CHANGAMPUZHA PARK","arrival_time":"6:20:39","distance":"13.07"},{"sr_no":"11","stn_name":"PALARIVATTOM","arrival_time":"6:23:10","distance":"14.43"}
],
[{"sr_no":"1","stn_name":"ALUVA","arrival_time":"5:59:30","distance":"1.81"},{"sr_no":"2","stn_name":"PULINCHUDU","arrival_time":"6:02:21","distance":"2.76"},{"sr_no":"3","stn_name":"COMPANYPADY","arrival_time":"6:04:19","distance":"3.76"},{"sr_no":"4","stn_name":"AMBATTUKAVU","arrival_time":"6:06:15","distance":"4.72"},{"sr_no":"5","stn_name":"MUTTOM","arrival_time":"6:08:11","distance":"8.14"},{"sr_no":"6","stn_name":"KALAMASSERY","arrival_time":"6:11:20","distance":"8.65"},{"sr_no":"7","stn_name":"CUSAT","arrival_time":"6:13:40","distance":"9.15"},{"sr_no":"8","stn_name":"PATHADIPALAM","arrival_time":"6:15:52","distance":"12.02"},{"sr_no":"9","stn_name":"EDAPPALLY","arrival_time":"6:18:12","distance":"12.55"},{"sr_no":"10","stn_name":"CHANGAMPUZHA PARK","arrival_time":"6:20:39","distance":"13.07"},{"sr_no":"11","stn_name":"PALARIVATTOM","arrival_time":"6:23:10","distance":"14.43"}]]
How to do this , because I have more than 900 record. In above I had showed only 2. Any suggestion will be appreciated, Thanks in advance. I am doing this for Android app

Parse the original JSON array string, and then add new JSON arrays containing up to 11 objects to a new array, adding each such array to another outer containing array:
// String input contains your string input JSON array
JSONArray jArray = new JSONArray(input); // your original JSON array
JSONArray outArray = new JSONArray(); // the output array of arrays
JSONArray temp = new JSONArray(); // holder for each internal array
for (int i=0; i < jArray.length(); i++) {
if (i % 11 == 0 && i > 0) {
outArray.put(temp);
temp = new JSONArray();
}
temp.put(jArray.getJSONObject(i));
}

Related

How to extract json Objects from String Builder?

I have string builder of the form:
[{"abc" : ["something1", "something2"]}, {"def" : ["something3", "something4"]}]
How do I convert it so that I can perform get on the keys? For e.g.: object.get("abc") and i get the list back.
I looked around for solutions:
I tried doing:
JSONObject jsonObject = new JSONObject(sb.toString());
I get the following exception:
exception org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
I then tried taking a sub-string of the Json, like this:
JSONObject jsonObject = new JSONObject(sb.toString().substring(1, sb.toString().length()-1));
which gives back:
jsonObjwct {"Z-DwY2Ul":["Worried Blues","Worried Blues"]}
I get only the first object, i need all of them.
What modifications i can do to get the list back for a specific key?
It is a JSONArray of JSONObject's, so first convert it into JSONArray
JSONArray array = new JSONArray(sb.toString());
And then you can iterate by using for loop
for (int i = 0, size = array.length(); i++) {
JSONObject obj = array.optJSONObject(i); //{"abc" : ["something1", "something2"]}
}

JSON Parse to Array value not appended properly

I have an array String[] cruce_no.I am appending Values from JSON response to the array. JSON response is a,b,c .... I need to append value Select to the 0th position of Array 'cruce_no'.
I need result like this {Select,a,b,c...}. But I am getting like this {Select,b,c...}. My code is below:
JSONArray JA=new JSONArray(result);
JSONObject json= null;
cruce_no = new String[JA.length()];
name = new String[JA.length()];
cruce_no[0] = "Select";
for(int i=0;i<JA.length();i++)
{
json=JA.getJSONObject(i);
cruce_no[i] = json.getString("
}
How can I solve this? Please help me.
Increase the size of the array by 1
cruce_no = new String[JA.length()+1];
cruce_no[0] = "Select";
Inside the forloop use this
cruce_no[i+1] = json.getString("YOUR_KEY");
You getting {Select,b,c...} instead of {Select,a,b,c...} because you add Select at 0th position so "a" replaced by "Select"
try like this
JSONArray JA=new JSONArray(result);
JSONObject json= null;
cruce_no = new String[JA.length()+1];
name = new String[JA.length()];
cruce_no[0] = "Select";
for(int i=0;i<JA.length();i++)
{
json=JA.getJSONObject(i);
cruce_no[i+1] = json.getString("
}
Make array size new String[JA.length()+1] as you are going to add an extra element select in it. And then place select at 0th positon followed by rest of the elements. So 0th position should not be overwritten.

Mapping JSON to arrays/objects in Java - Android

I have a web system that returns a json string with the data that I need in an Android App. The string is below:
[
{"id":1,
"title":"Remove ViRuSeS",
"tagline":"Remove ViRuSeS",
"body":"Body",
"image":"index.jpg",
"steps":[
{"id":2,
"title":"Step 1",
"body":"Download Things!",
"position":1}
]
}
]
It should return an array of objects, with one of the object's items also being an array of items.
I am familiar with gson and have gotten this working in the past, but I always had to simplify my data down to just an object, which makes me end up have to make multiple calls to get the data.
Is there a good way to do this without having to map all of the possible values back into classes?
My last attempt was to just try to get something simple out of this and am getting a NullPointerException on the second of these lines:
userDet = new JSONObject(string);
JSONArray userDetJson = userDet.getJSONArray("Steps");
change it to "steps" and not "Steps" , It will fix it:
userDet = new JSONObject(string);
JSONArray userDetJson = userDet.getJSONArray("steps");
The full parsing method:
JSONArray mainArray = new JSONArray(json);
for (int i = 0 ; i < mainArray.length() ; i ++)
{
JSONObject currentItem = array.getJSONObject(i);
String title = currentItem.getString("title");
String body = currentItem.getString("body ");
....
JSONArray currentItemStepsArray = currentItem.getJSONArray("steps");
for (int j = 0 ; j < currentItemStepsArray.length() ; j ++)
{
....
}
}
Here, try this:
JSONArray topLevelArr = new JSONArray(json);
JSONArray stepArr = topLevelArr.getJSONObject(0).getJSONArray("steps");

How to parse a JSONArray of JSONObjects in JAVA?

I have the following array returned to my JAVA Android application from PHP:
Array ( [0] => Array ( [referral_fullname] => Name 1 [referral_balance] => 500 ) [1] => Array ( [referral_fullname] => Name 2 [referral_balance] => 500 ) );
In Java they above array looks like this:
{"0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}};
For a simple JSONObject I'm using:
JSONTokener tokener = new JSONTokener(result.toString());
JSONObject finalResult = new JSONObject(tokener);
referral_fullname = finalResult.getString("referral_fullname");
but for an array of objects I don't know!
String str = your Json-> apply to.String();
JSONObject jObject = new JSONObject(str);
Map<String,String> map = new HashMap<String,String>();
Iterator iter = jObject.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = jObject .getString(key);
map.put(key,value);
}
Your Json Syntax is wrong , JSONArray should be like this :
["0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}];
and to parse a JsonArray that contains some JSONObject , try this :
//parse the result
JSONObject jsonResult = null;
JSONArray arrayResult = null;
ArrayList<YourObject> listObjects = null;
try {
arrayResult = new JSONArray(result);
if(arrayResult != null) {
listObjects = new ArrayList<YourObject>();
int lenght = arrayResult.length();
for(int i=0; i< lenght; i++) {
JSONObject obj = arrayResult.getJSONObject(i);
YourObject object = new YourObject(obj);
listObjects.add(object);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
And add a constructor in your Class YourObject to convert your Json to an instance :
public YourObject(JSONObject json) {
if (!json.isNull("referral_fullname"))
this.referral_fullname = json.optString("referral_fullname", null);
if (!json.isNull("referral_balance"))
this.referral_balance = json.optString("referral_balance", null);
}
You should use
JSONArray finalResult = new JSONArray(tokener);
if you can. You structure is now an object with two fields, 0 and 1, which contains another object. You have to get an array of object in place of this composite object if you want to iterate easily like
JSONObject jso;
for(int i = finalResult.lenght-1; i >=0; i--){
jso = finalResult.get(i);
// jso == {"referral_fullname":"Name 1","referral_balance":"500"}
[whatever]
}
Try this.............
final JSONArray result_array = json.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
JSONObject joObject = result_array.getJSONObject(i);
String jName = joObject.get("referral_fullname").toString();
String jbalance = joObject.get("referral_balance").toString();
}
First make an JSON object and see then in inner level what you have if you have array then fetch array.
You need to make JSON object first. For example, if resp is a String (for example coming as http response)
JSONObject jsonObject = new JSONObject(resp);
jsonObject may contains other JSON Objects or JSON array. How to convert the JSON depends on the response.
If arraykey is a array inside the JSON objects then we can get list of array by the following way.
JSONArray arr = jsonObject.getJSONArray("arraykey");
Check the length of arr, if it is greater than 0 then it contains JSON objects or JSON array depending the data.
There is a complete example with some explanation about JSON String to JSON array can be found at
http://www.hemelix.com/JSONHandling

json in java getting the correct values from a list

I am using the package org.json package: I need help with getting the corect data from the json in java. this is the string I have in json:
{"GetLocationsResult":[{"ID":82,"Name":"Malmo","isCity":true,"isCounty":false,"isDisctrict":false,"ID_Parent":null,"ID_Map":35,"ZipCode":"7000"},{"ID":82,"Name":"Trelleborg","isCity":true,"isCounty":false,"isDisctrict":false,"ID_Parent":null,"ID_Map":35,"ZipCode":"7000"}]}
This is a listing and this is just a test, it will contain more than 2 items, so my questions is, I want to get the name of all locations, I want to populate a spinner with names in my android app.
How can I get the "Name":"Malmo" and so on....
???
The answer is simple....The JSON element starts with a { which is a JSON Object, and GetLocationsResults is a JSON Array of JSON Objects. In essence, I translated the JSON String to the following code...
JSONObject rootJson = new JSONObject(jsonString);
JSONArray jsonArray = rootJson.getJSONArray("GetLocationsResult");
//Let's assume we need names....
String[] names = null;
if (jsonArray != null) {
names = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
names[i] = json.getString("Name");
}
}
//Test
for (String name: names) {
System.out.println(name);
}

Categories