I have a JSONArray of JSONObjects in each of which is a string with the key "kind". I'm trying to loop through the JSONarray and organize them by "kind" to use to fill a SeperatedListAdapter. what I am trying to achieve is this structure
{
communications[
{ "header":"kind"
communications[
{}
{}
{}
{}
]
}
{ "header":"kind"
communications[
{}
{}
{}
{}
]
}
]
}
The problem I'm having is the for loop i have created to achieve this gets stuck in an endless loop and thus crashes the application. Does anyone know where I am going wrong with this?
Here's my code I know it gets stuck in a loop as it runs the log "1" about 1000 times even though I know there's only 5 things in the array I'm passing in.
for(int i = 0; i < communicationsFromFile.length(); i++){
JSONObject communication = communicationsFromFile.getJSONObject(i);
Log.v("Communications", "kind = " + communication.getString("kind"));
Log.v("Communications", "newComArray = " + newComArray);
if(newComArray.length() != 0){
Log.v("Communications", "newComArray IsNotempty");
for(int a = 0; a < newComArray.length();a++){
JSONObject itemInArray = newComArray.getJSONObject(a);
JSONArray communicationsForKind = itemInArray.getJSONArray("communications");
Log.v("Communications", "1");
if(itemInArray.getString("header").equals(communication.getString("kind"))){
Log.v("Communications", "Header Exists");
communicationsForKind.put(communication);
itemInArray.put("communications", communicationsForKind);
newComArray.put(itemInArray);
}else{
Log.v("Communications", "Header Does not Exist");
JSONObject addItemInArray = new JSONObject();
JSONArray addArrayToItem = new JSONArray();
addArrayToItem.put(communication);
addItemInArray.put("header", communication.getString("kind"));
addItemInArray.put("communications", addArrayToItem);
newComArray.put(addItemInArray);
}
}
}else{
JSONObject addItemInArray = new JSONObject();
JSONArray addArrayToItem = new JSONArray();
addArrayToItem.put(communication);
addItemInArray.put("header", communication.getString("kind"));
addItemInArray.put("communications", addArrayToItem);
newComArray.put(addItemInArray);
}
}
In each iteration of the inner for loop, you put new objects in the newComArray. The condition a < newComArray.length() is always satisfied because a and the array length both grow at the same rate.
Related
I have following data from JSON
{
"MenuName": "starter dish",
"SubMenu": [
"pizza dish1",
"pizza dish2"
],
"Price": [
"100",
"110"
]
},
From here i can easily fetch data from "Menuname" key as starter dish but when I fetch data from "Submenu" I get whole string as ["pizza dish1", "pizza dish2"].
Please suggest me way to differentiate both pizza dish1 and pizza dish2
Submenu and Price is not String it is JSONArray so you will need to use for-loop to get all values from Submenu JSONArray as:
JSONArray jsonsubmenu=yourjsonobject.getJSONArray("Submenu");
for(int i=0;i < jsonsubmenu.length();i++){
// get all values from jsonsubmenu JSONArray..
String str_value=jsonsubmenu.optString(i);
....
}
try this
for (int i = 0; i < jsonArray.length(); i++) {
jsonArray.getJSONObject(i).getInt("SubMenu");
}
you can use this link for creating POGO class for your response. It will automatically generate class for your response.
Use google GSON library to parse your response.
or you can simply create a JSON Array or Objects to parse it. in your case it is JSON Object or JSON arrays.
Hi There in that senarerio you have to use
JSONArray _submenu = object.getJSONArray("SubMenu");
for (int i = 0; i < _submenu.length(); i++) {
String text = _submenu.getString(i);
}
JSONArray _price = object.getJSONArray("Price");
for (int i = 0; i < _price.length(); i++) {
String text = _price.getString(i);
}
You can retrieve array values and store it in string[] and use them as per your need. i.e., as follows..
try {
JSONObject jObject = new JSONObject(jsonString);
JSONArray jSubmenu = jObject.getJSONArray("SubMenu");
subMenu = new String[jSubmenu.length()];
for (int i = 0; i < subMenu.length; i++) {
subMenu[i] = jSubmenu.getString(i);
}
JSONArray jPrice = jObject.getJSONArray("Price");
price = new String[jPrice.length()];
for (int i = 0; i < price.length; i++) {
price[i] = jPrice.getString(i);
}
} catch (Exception e) {
// TODO: handle exception
}
Just to throw in a quickie - read up on, and use GSON.
For simple small jobs I find it is the best. Not the fastest running for complex, or long structures, but really quick on the dev side.
Here's the link: google-gson
In my app, i want to parse json response which is in the format
{"quote":[{"orderId":"3209926"},{"totalpages":1}]}
below is the code which i had done,But the problem is how to get the "totalpages" value?
try {
JSONObject jObject = new JSONObject(result);
JSONArray jArray = jObject.getJSONArray("quote");
for (int i = 0; i < jArray.length(); i++)
{
JSONObject offerObject = jArray.getJSONObject(i);
current.orderId = offerObject.getInt("orderId");
It shows error when i use
current.totalpage= offerObject.getInt("totalpages");
Anybody knows how to parse this?THanks in advance
Note that getInt(), like other get-functions of JSONObject throw JSONException if the object does not contain the key requested. Thus, before you request the key you should use hasKey() to determine whether the object contains the key.
For example, inside the for loop you can do the following:
JSONObject offerObject = jArray.getJSONObject(i);
if(offerObject.has("orderId") {
current.orderId = offerObject.getInt("orderId");
}
if(offerObject.has("totalpages") {
current.totalpage= offerObject.getInt("totalpages");
}
You can also add a flag and a check after the loop to ensure that both orderId and totalpages were present in the JSON data.
I dont know why your json is having that structure. But if you want to parse it then you will have to do something like the following with the has function.
for (int i = 0; i < jArray.length(); i++) {
JSONObject offerObject = jArray.getJSONObject(i);
if(offerObject.has("orderId")) {
current.orderId = offerObject.getInt("orderId");
} else if(offerObject.has("totalpages")) {
current.totalpage= offerObject.getInt("totalpages");
}
}
i have an array from a json feed i know that in the jArray there is one league but i need to work out the count of that array incase a second is added to the feed at a later date. at the moment log cat isn't logging out "teamFeedStructure" does anyone know what I'm doing wrong or know how to correctly turn the length of an array into a string that i can use in an intent?
heres the code
JSONObject obj = new JSONObject(json);
JSONObject objData = obj.getJSONObject("data");
JSONArray jArray = objData.getJSONArray("structure");
//String leagues = jArray.toString();
//Log.v("myapp", "structure" + leagues);
for (int i=0; i < jArray.length(); i++) {
JSONObject oneObject = jArray.getJSONObject(i);
leaguecountArray = oneObject.getJSONArray("league_id");
for (int l=0; l < leaguecountArray.length(); l++) {
if (leaguecountArray.length() == 1) {
teamFeedStructure = "One";
}
if (leaguecountArray.length() == 2) {
teamFeedStructure = "Two";
}
Log.v("myapp", teamFeedStructure);
}
}
Why do you need to iterate here:
for (int l=0; l < leaguecountArray.length(); l++)
{
if (leaguecountArray.length() == 1){
teamFeedStructure = "One";
}
if (leaguecountArray.length() == 2){
teamFeedStructure = "Two";
}
Log.v("myapp", teamFeedStructure);
}
Nevermind how many passes you do the result will still be the same.
Also you can use not English words, but String holding the number you need. Do like that:
teamFeedStructure = String.valueOf(leaguecountArray.length());
Then the value will become "2" for example. In your other activity you can parse it again to integer like that: int number = Integer.parseInt(teamFeedStructure);
Add the following line
teamFeedStructure = "greater two";
before
if (leaguecountArray.length() == 1){
If you get greater two message, means your array length more than two.
Thanks for your help everyone i discovered that i had gone a step too far into the feed which is why i was not getting anything in Logcat. now it's counting fine.
[{"placeID":"p0001","placeName":"INTI International University","placeType":"Education","placeLat":"2.813997","placeLng":"101.758229","placePict":""},{"placeID":"p0002","placeName":"Nilai International College","placeType":"Education","placeLat":"2.814179","placeLng":"101.7700107","placePict":""}]
How do I decode the JSON sent from my PHP script on Android?
please try this
String s = "[{\"placeID\":\"p0001\",\"placeName\":\"INTI International University\",\"placeType\":\"Education\","
+ "\"placeLat\":\"2.813997\",\"placeLng\":\"101.758229\",\"placePict\":\"\"},"
+ "{\"placeID\":\"p0002\",\"placeName\":\"Nilai International College\",\"placeType\":\"Education\",\"placeLat\":\"2.814179\",\"placeLng\":\"101.7700107\",\"placePict\":\"\"}]";
ArrayList<String> arrplaceID = new ArrayList<String>();
ArrayList<String> arrplaceName = new ArrayList<String>();
try {
JSONArray arr = new JSONArray(s);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonObject = arr.getJSONObject(i);
arrplaceID.add(jsonObject.optString("placeID"));
arrplaceName.add(jsonObject.optString("placeName"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < arrplaceID.size(); i++) {
Log.e("arr[" + i + "] place Name", arrplaceName.get(i));
}
What is the problem in this Please Read this tutorial for parsing JSON it might be helpful in future also.json parsing link
Follow below points.
1) it seems the response you are getting is Json Array. so create one json array by response string.
JSonArray jArray = new JsonArray(responseString);
2) now you have your response in jArray. now iterate a loop and take json object from JsonArray, in your case you have two json objects.
for(i,i<jArray.size,i++)
{
JsonObject obj=jArray.get(i);
// here you got your first entry in jsonObject.
// nor use this obj according to ur need. you can say obj.getString("placeID");
// and so on.
}
refer this to understand more on json link
use JSONArray class:
JSONArray jsonplaces = new JSONObject(stringPlaces);
then your able to iterate throught array by using for-loop:
for (int i = 0; i < jsonplaces.length(); i++) {
JSONObject jsonplace = (JSONObject) jsonplaces.get(i);
//read items, for example:
String placeName = jsonplace.getString("placeName");
}
I have a json object:
"images":{"1":{"imagename":"image1.gif","url":"image1url"},"2":{"imagename":"image2.gif","url":"image2url"},"3":{"imagename":"image3.gif","url":"image3url"}}
I want to fetch imagename and url from this. I enter into this images. I fetched the values 1,2,3 from images. But I am not able to fetch the json corresponding to this 1,2 and 3.
Its throwing exception stating: No value for 1
or No Value for 2
or No value for 3
What may be the reason for this cause? Please reply..
My present code is:
if(jsonObj.has("images")) {
JSONArray imagesArray = jsonObj.getJSONObject("images").names();
JSONObject imageDetailsObject;
for(int i = 0; i < imagesArray.length(); i++) {
imageDetailsObject = jsonObj.getJSONObject(imagesArray.get(i).toString());
if(imageDetailsObject.has("imagename")) {
//perform some actions
}
if(imageDetailsObject.has("url")) {
//perform some actions
}
}
}
EDITED:
imageDetailsObject = jsonObj.getJSONObject("images").getJSONObject(imagesArray.get(i).toString());
I got it worked by giving:
if (jsonObj.has("images")) {
JSONArray imagesArray = jsonObj.getJSONObject("images").names();
JSONObject imageDetailsObject;
for (int i = 0; i < imagesArray.length(); i++) {
imageDetailsObject = jsonObj.getJSONObject("images").getJSONObject(
imagesArray.getString(i));
if(imageDetailsObject.has("imagename")) {
//perform some actions
}
if (imageDetailsObject.has("url")) {
//perform some actions
}
}
}