I have the following JSONarray and I need to have the output like below. Help please.
{
"data": [
{
"Mandal": "Rambilli",
"Village": "Chatametta"
},
{
"Mandal": "Anakapalle",
"Village": "Valluru"
},
{
"Mandal": "Anakapalle",
"Village": "Venkupalem"
},
{
"Mandal": "Rambilli",
"Village": "Chebrolu Konda"
},
{
"Mandal": "Anakapalle",
"Village": "Vetajangalapalem"
},
{
"Mandal": "Anakapalle",
"Village": "Vooderu"
}
]
}
The out put needs to be two lists with names of Mandal
List<String> Rambilli to contain [Chatametta, Chebrolu Konda]
List Anakapalle to contain [Valluru, Venkupalem, Vetajangalapalem, Vooderu]
The major roadblock I'm facing is how to put the name of the mandal to the output list.
I hard coded every thing but Try:
List<String> listOfRambilli = new ArrayList<>();
List<String> listOfAnakapalle = new ArrayList<>();
try {
JSONArray dataArray = jsonData.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
JSONObject objectInsideDataArray = dataArray.getJSONObject(i);
String village = objectInsideDataArray.getString("Village");
String mandal = objectInsideDataArray.getString("Mandal");
if (mandal.equals("Rambilli"))
listOfRambilli.add(village);
else if (mandal.equals("Anakapalle"))
listOfAnakapalle.add(village);
else
throw new NoSuchElementException();
}
Log.d("TAG", "" + listOfAnakapalle);
Log.d("TAG", "" + listOfRambilli);
} catch (JSONException e) {
e.printStackTrace();
}
Try this way:
JSONArray jsonArray = jsonObject.getJSONArray("data");
ArrayList<String> rambilliList = new ArrayList<>();
ArrayList<String> anakapalleList = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject listJsonObject = jsonArray.getJSONObject(i);
if(listJsonObject.getString("Mandal").equals("Rambilli")){
rambilliList.add(listJsonObject.getString("Village"));
} else if(listJsonObject.getString("Mandal").equals("Anakapalle")) {
anakapalleList.add(listJsonObject.getString("Village"));
}
}
System.out.println("Rambilli contains" + rambilliList)
System.out.println("Anakapalle contains" + anakapalleList)
Related
I am getting null pointer error while converting string to json object i have tried gson,parser etc but none seems to be working.
Can somebody provide a solution for below response (I have done substring in order to remove "data: "):
data: {
"C": "abc",
"A": [{
"B": "BcastHub",
"C": "onData",
"D": [{
"ID": "1",
"One": [{
"Plus": 5.0,
"Minus": 93400.0
}, {
"Plus": 4.9,
"Minus": 8570.0
}, {
"Plus": 4.8,
"Minus": 140606.0
}],
"Two": [{
"Plus": 5.1,
"Minus": 34.0
}, {
"Plus": 5.2,
"Minus": 44622.0
}, {
"Plus": 5.3,
"Minus": 2408.0
}]
}]
}]
}
My code for Fetching
try{
URL urlData = new URL(url);
BufferedReader reader = new BufferedReader(new InputStreamReader(
urlData.openConnection().getInputStream(), "utf-8"));
String struct = reader.readLine();
while ((struct = reader.readLine()) != null ) {
if(!struct.equals("")) {
struct = struct.substring(6,struct.length());
JSONParser parser = new JSONParser();
JSONObject lev1 =(JSONObject) parser.parse(struct);
//JSONObject lev1 = (JSONObject) obj;
JSONObject parent = (JSONObject) lev1.get("A");
for(int j=0;j<parent.length();j++) {
JSONObject child1 = (JSONObject) parent.get("D");
JSONArray child2 = (JSONArray) child1.get("One");
for (int i = 0; i < child2.length(); i++) {
JSONObject item = child2.getJSONObject(i);
final String plus = item.getString("Plus");
final String minus = item.getString("Minus");
runOnUiThread(new Runnable() {
#Override
public void run() {
tv.setText("Plus => " + plus + "Minus = > " + minus);
}
});
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
Tell me if you want anything else. Thanks.
Edit : I am trimming the start of the string in order to make it in proper format and then converting the string to JSONObject is giving me error. at JSONObject parent = (JSONObject) lev1.get("A"); as lev1 is null.
try {
jsonResponse = new JSONObject(strJson2);
JSONObject user = jsonResponse.getJSONObject("data");
num = user.getString("C");
JSONArray user1 = user.getJSONArray("A");
for (int i = 0; i < user1.length(); i++) {
jsonChildNode = user1.getJSONObject(i);
String B = jsonChildNode.getString("B");
String c2 = jsonChildNode.getString("C");
Toast.makeText(this, B + "::" + c2.toString(), Toast.LENGTH_SHORT).show();
JSONArray jsonArraysunject = jsonChildNode.getJSONArray("D");
for (int j = 0; j < jsonArraysunject.length(); j++) {
JSONObject DD = jsonArraysunject.getJSONObject(j);
String dd = DD.getString("ID");
Toast.makeText(this, dd.toString(), Toast.LENGTH_SHORT).show();
One = DD.getJSONArray("One");
for (int k = 0; k < One.length(); k++) {
// for (int i = 0; i < lengthJsonArr; i++) {
jsonChildNodeo = One.getJSONObject(k);
type = jsonChildNodeo.getString("Plus");
num = jsonChildNodeo.getString("Minus");
makeText.add("Plus - " + type);
makeText.add("Minus - " + num);
Toast.makeText(this, makeText.toString(), Toast.LENGTH_SHORT).show();
}
Toast.makeText(this, "hdjeh", Toast.LENGTH_SHORT).show();
Two = jsonChildNodeo.getJSONArray("Two");
Toast.makeText(this, Two.toString(), Toast.LENGTH_SHORT).show();
for (int r = 0; r < Two.length(); r++) {
JSONObject tw = Two.getJSONObject(r);
String tplus = tw.getString("Plus");
String tminus = tw.getString("Minus");
makeText2.add("plus - " + tplus);
makeText2.add("minus - " + tminus);
Toast.makeText(this, makeText2.toString(), Toast.LENGTH_SHORT).show();
// }
}
}
Just place your json data in jsonString vairable and that's all.
try {
JSONObject mainObject=new JSONObject(jsonString);
System.out.println(mainObject.toString());
System.out.println("// First Level object(s)");
System.out.println("C--> "+mainObject.getString("C"));// First Level object C
JSONArray firstArray=mainObject.getJSONArray("A");
for(int i=0;i<firstArray.length();i++){ //First Level Array A
JSONObject arrayObject =firstArray.getJSONObject(i);
System.out.println("// Second Level object(s)");
System.out.println("B--> "+arrayObject.getString("B")); // Second Level Object B
System.out.println("C--> "+arrayObject.getString("C")); // Second Level Object C
System.out.println("//Second Level Array D");
JSONArray secondLevelArray=arrayObject.getJSONArray("D");
for(int j=0;j<secondLevelArray.length();j++){
JSONObject innerArrayObject=secondLevelArray.getJSONObject(j);
System.out.println("// Third Level object(s) ");
System.out.println("ID --> "+innerArrayObject.getString("ID"));
JSONArray thirlLevelArray1=innerArrayObject.getJSONArray("One");
for(int k=0;k<thirlLevelArray1.length();k++){
JSONObject innerMostObjects=thirlLevelArray1.getJSONObject(k);
System.out.println("Plus -->"+innerMostObjects.get("Plus"));
System.out.println("Minus -->"+innerMostObjects.get("Minus"));
}
JSONArray thirlLevelArray2=innerArrayObject.getJSONArray("Two");
for(int k=0;k<thirlLevelArray2.length();k++){
JSONObject innerMostObjects=thirlLevelArray2.getJSONObject(k);
System.out.println("Plus -->"+innerMostObjects.get("Plus"));
System.out.println("Minus -->"+innerMostObjects.get("Minus"));
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I parsed your data using Gson. The advantages of Gson are discussed previously. In addition, you can check goals of Gson.
Here is how to parse your data using Gson:
Note that I have not used code formatting standards (for example, the name of a class should use CamelCase) because you couldn't share real data.
Extracting JSON string:
While extracting JSON string use indexOf(int) instead of hard-coded 6.
jsonString = jsonString.substring(jsonString.indexOf("{"));
Parsing:
Gson gson = new Gson();
data d = gson.fromJson(reader, data.class);
for (a a1 : d.A) {
for (plusminus pm : a1.D[0].One) {
System.out.println("Plus => " + pm.Plus + " Minus => " + pm.Minus);
}
}
Required Classes:
public class data {
public String C;
public a A[];
}
public class a {
public String B;
public String C;
public d D[];
}
public class d {
public int ID;
public plusminus One[], Two[];
}
public class plusminus {
public double Plus;
public double Minus;
}
I need to parse my JSON to my Android application, I’m getting an error:
org.json.array cannot be converted to jsonobject
What I want to do is to take the json from my server and parse it into the textviews that i had made I’m using AsyncHttpClient, here is my code.
AsyncHttpClient client1 = new AsyncHttpClient();
client1.get("http://mahmoudfa-001-site1.atempurl.com/appetizers.json",new
TextHttpResponseHandler() {
#Override
public void onFailure ( int statusCode, Header[] headers, String responseString, Throwable throwable){
}
#Override
public void onSuccess ( int statusCode, Header[] headers, String responseString){
Log.i("a1", responseString);
//testing if the server responding.
Toast.makeText(getApplicationContext(), responseString, Toast.LENGTH_LONG).show();
try {
JSONObject job = new JSONObject(responseString);
JSONArray arr = new JSONArray(build);
//String arrlen = Integer.toString(arr.length());
JSONObject na = arr.getJSONObject(0);
JSONArray ingna = na.getJSONArray("unavailable");
String[] ingr = new String[ingna.length()];
for (int k = 0; k < ingna.length(); k++) {
JSONObject abc = ingna.getJSONObject(k);
ingr[k] = abc.getString("ingredient");
}
for (int i = 1; i < arr.length(); i++) {
JSONObject food = null;
food = arr.getJSONObject(i);
String name = food.getString("name");
String description = food.getString("description");
String rating = food.getString("rating");
String price = food.getString("price");
String cooktime = food.getString("cooktime");
JSONArray ingredients = food.getJSONArray("ingredients");
String[] ing = new String[ingredients.length()];
for (int k = 0; k < ingredients.length(); k++) {
JSONObject ingd = ingredients.getJSONObject(k);
ing[k] = ingd.getString("ingredient");
}
for (int l = 0; l < ing.length; l++) {
for (int m = 0; m < ingr.length; m++) {
if (ing[l].matches(ingr[m])) ;
}
}
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
JSONObject job = new JSONObject(responseString);
JSONArray arr = new JSONArray(build);
//String arrlen = Integer.toString(arr.length());
JSONObject na = arr.getJSONObject(0);
JSONArray ingna = na.getJSONArray("unavailable");
String[] ingr = new String[ingna.length()];
for (int k = 0; k < ingna.length(); k++) {
JSONObject abc = ingna.getJSONObject(k);
ingr[k] = abc.getString("ingredient");
}
for (int i = 1; i < arr.length(); i++) {
JSONObject food = null;
food = arr.getJSONObject(i);
String name1 = food.getString("name");
if (name.equals(name1)) {
imageUrl[0] = imageUrl[0] + i;
nametext.setText("Name : " + name);
String description = food.getString("description");
detailstext.setText("Description : " + description);
String rating = food.getString("rating");
String price = food.getString("price");
price1 = Integer.parseInt(price);
pricetext.setText("Price : Rs. " + price);
ratingtext.setText("Rating : " + rating + " stars");
String cooktime = food.getString("cooktime");
cooktimetext.setText("Cooktime : " + cooktime);
JSONArray ingredients = food.getJSONArray("ingredients");
String[] ing = new String[ingredients.length()];
for (int k = 0; k < ingredients.length(); k++) {
JSONObject ingd = ingredients.getJSONObject(k);
ing[k] = ingd.getString("ingredient");
}
String ingre = "Ingredients:";
for (int k = 0; k < ing.length; k++) {
if (k < (ing.length - 1))
ingre = ingre + " " + ing[k] + ",";
else
ingre = ingre + " " + ing[k];
}
ingredientstext.setText(ingre);
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Please I need help..
this is the JSON I am getting from my server:
[
{
"unavailable" :
[
{
"ingredient" : "Prawn"
},
{
"ingredient" : "Paneerygf"
},
{
"ingredient" : "Fish1"
}
]
},
{
"name" : "Paneer Chilly",
"description" : "Fried paneer pieces in chilly gravy",
"rating" : "4",
"price" : "100",
"cooktime" : "20 mins",
"ingredients" : [
{"ingredient":"Paneer"}
]
},
{
"name" : "Prawn Stuff Papad",
"description" : "Papad stuffed with prawns and spices",
"rating" : "3",
"price" : "150",
"cooktime" : "25 mins",
"ingredients" : [
{"ingredient":"Prawn"}
]
},
{
"name" : "Fish Chilly",
"description" : "Fired fish fillets with chilly gravy",
"rating" : "3",
"price" : "175",
"cooktime" : "25 mins",
"ingredients" : [
{"ingredient":"Fish"}
]
}
]
The response returned from http://mahmoudfa-001-site1.atempurl.com/appetizers.json is a JSONArray, not a JSONObject. You should parse it by JSONArray jsonArray = new JSONArray(responseString).
I'm having trouble getting the String "lf" in this case North Atlantic Treaty Organization
[
{
"sf": "NATO",
"lfs": [
{
"lf": "North Atlantic Treaty Organization",
"freq": 13,
"since": 2001,
"vars": [
{
"lf": "North Atlantic Treaty Organization",
"freq": 13,
"since": 2001
}
]
}
]
}
]
//MY CODE
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray(ITEM_TAG);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
String name = c.getString("lf");
acronyms = new ArrayList<>();
acronyms.add(name);
}
} catch (Exception e) {
}
try {
JSONArray jsonArray1 = new JSONArray(JsonString);
for (int i = 0; i <= jsonArray1.length(); i++) {
JSONObject jsonObject2 = jsonArray1.getJSONObject(i);
String mStrSf = jsonObject2.getString("sf");
Toast.makeText(getApplicationContext(),mStrSf.toString(), Toast.LENGTH_LONG).show();
JSONArray jsonArray3 = jsonObject2.getJSONArray("lfs");
for (int j = 0; j <= jsonArray3.length(); j++) {
JSONObject jsonObject4 = jsonArray3.getJSONObject(j);
String mStrIf = jsonObject4.getString("lf");
String mStrFreq = jsonObject4.getString("freq");
String mStrSince = jsonObject4.getString("since");
Toast.makeText(getApplicationContext(),mStrIf+"\n"+mStrFreq+"\n"+mStrSince, Toast.LENGTH_LONG).show();
JSONArray jsonArray5 = jsonObject4.getJSONArray("vars");
for (int k = 0; k <= jsonArray5.length(); k++) {
JSONObject jsonObject6 = jsonArray5.getJSONObject(k);
String mStrIf1 = jsonObject6.getString("lf");
String mStrFreq1 = jsonObject6.getString("freq");
String mStrSince1 = jsonObject6.getString("since");
Toast.makeText(getApplicationContext(),mStrIf1+"\n"+mStrFreq1+"\n"+mStrSince1, Toast.LENGTH_LONG).show();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
You are interpreting the json in a wrong way... if you analyse the json chain you will get this:
as you can see you have an array inside and array...
hope the picture helps you to see it better.
You have to again loop through the jsonArray to get "lf" key value.
Try this...
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray(ITEM_TAG);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
JSONArray array = c.getJSONArray("lfs");
for(int j=0;j<array.length();j++){
JSONObject obj = array.getJSONObject(j);
String name = obj.getString("lf");
}
}
} catch (Exception e) {
}
I have created two JSON like following,
First Array:
[
{
"id":255,
"is_new":0,
"is_checked":true,
"name":"Towel Rack 650",
"is_favourite":false
},
{
"id":257,
"is_new":0,
"is_checked":true,
"name":"Towel Rod 450",
"is_favourite":false
},
{
"id":259,
"is_new":0,
"is_checked":true,
"name":"Napkin Ring - Round",
"is_favourite":false
}
]
Second Array:
[
{
"id":258,
"is_new":0,
"is_checked":false,
"name":"Towel Rod 650",
"is_favourite":true
},
{
"id":259,
"is_new":0,
"is_checked":false,
"name":"Napkin Ring - Round",
"is_favourite":true
}
]
In that I have to merge both array and also want to keep duplicate values once in final array.
I used following snippet for merging.
private JSONArray concatArray(JSONArray arr1, JSONArray arr2)
throws JSONException {
JSONArray result = new JSONArray();
for (int i = 0; i < arr1.length(); i++) {
result.put(arr1.get(i));
}
for (int i = 0; i < arr2.length(); i++) {
result.put(arr2.get(i));
}
return result;
}
I am getting:
[
{
"id":255,
"is_new":0,
"is_checked":true,
"name":"Towel Rack 650",
"is_favourite":false
},
{
"id":257,
"is_new":0,
"is_checked":true,
"name":"Towel Rod 450",
"is_favourite":false
},
{
"id":259,
"is_new":0,
"is_checked":true,
"name":"Napkin Ring - Round",
"is_favourite":false
},
{
"id":258,
"is_new":0,
"is_checked":false,
"name":"Towel Rod 650",
"is_favourite":true
},
{
"id":259,
"is_new":0,
"is_checked":false,
"name":"Napkin Ring - Round",
"is_favourite":true
}
]
In that I am getting duplicate values of id 259 which has different values of is_checked and is_favourite which I want true value for both like:
{
"id":259,
"is_new":0,
"is_checked":true,
"name":"Napkin Ring - Round",
"is_favourite":true
}
I have also tried SparseArray but not succeed. Is there any way to do this?
Your help would be appreciated.
Alright, I wrote the code for you:
First, preparing the objects:
JSONArray arr1 = new JSONArray(),arr2 = new JSONArray(),result = new JSONArray();
JSONObject jobj = new JSONObject();
try {
jobj.put("id", "255");
jobj.put("is_new", 0);
jobj.put("is_checked", true);
jobj.put("name", "Towel Rack 650");
jobj.put("is_favourite", false);
arr1.put(jobj);
jobj = new JSONObject();
jobj.put("id", "257");
jobj.put("is_new", 0);
jobj.put("is_checked", true);
jobj.put("name", "Towel Rod 450");
jobj.put("is_favourite", false);
arr1.put(jobj);
jobj = new JSONObject();
jobj.put("id", "259");
jobj.put("is_new", 0);
jobj.put("is_checked", true);
jobj.put("name", "Napkin Ring - Round");
jobj.put("is_favourite", false);
arr1.put(jobj);
jobj = new JSONObject();
jobj.put("id", "258");
jobj.put("is_new", 0);
jobj.put("is_checked", false);
jobj.put("name", "Towel Rod 650");
jobj.put("is_favourite", true);
arr2.put(jobj);
jobj = new JSONObject();
jobj.put("id", "259");
jobj.put("is_new", 0);
jobj.put("is_checked", false);
jobj.put("name", "Napkin Ring - Round");
jobj.put("is_favourite", true);
arr2.put(jobj);
result = concatArray(arr1, arr2);
} catch (JSONException e) {
e.printStackTrace();
}
Then, the method:
private JSONArray concatArray(JSONArray arr1, JSONArray arr2)
throws JSONException {
JSONArray result = new JSONArray();
JSONObject jobj1 = new JSONObject(),jobj2 = new JSONObject(),tmpobj = new JSONObject();
Set<String> objectsList = new HashSet<String>();
for (int i = 0; i < arr1.length(); i++) {
if(objectsList.add(arr1.getJSONObject(i).getString("id"))){
result.put(arr1.getJSONObject(i));
}
}
for (int i = 0; i < arr2.length(); i++) {
if(objectsList.add(arr2.getJSONObject(i).getString("id"))){
result.put(arr2.getJSONObject(i));
} else {
jobj1 = arr2.getJSONObject(i);
int index = 0;
for(int j = 0; j < result.length(); j++){
if(result.getJSONObject(j).getString("id").equals(jobj1.getString("id"))){
jobj2 = result.getJSONObject(j);
index = j;
}
}
tmpobj.put("id", jobj2.getString("id"));
tmpobj.put("is_new", jobj2.getInt("is_new"));
if(jobj1.getBoolean("is_checked")||jobj2.getBoolean("is_checked")){
tmpobj.put("is_checked", true);
} else {
tmpobj.put("is_checked", false);
}
tmpobj.put("name", jobj2.getString("name"));
if(jobj1.getBoolean("is_favourite")||jobj2.getBoolean("is_favourite")){
tmpobj.put("is_favourite", true);
} else {
tmpobj.put("is_favourite", false);
}
result.put(index, tmpobj);
}
}
return result;
}
You can add a SparseArray(key:id,value:each JSONObject in your JSONArray) to save your jsonobjects,every get a jsonobject,first check if its id has existed in SparseArray,if not,insert it.or you will do your logic to decide whether to insert it or update it or ignore it.
At last,if you want to get a JSONArray as return type,then add all SparseArray's values to your JSONArray result.
how I can access data from a JSONArray? It is this and contains this information:
"deadlines": [
{
"start": 1439539200,
"end": 1439542800
},
{
"start": 1440144000,
"end": 1440147600
},
{
"start": 0,
"end": 0
}
]
I need to have in a String tag each item "start". Thanks
EDIT
My code is this:
JSONArray array = moduleObject.specialForcedConf;
// array = [{"deadlines":[{"start":1439539200,"end":1439542800},{"start":1440144000,"end":1440147600},{"start":0,"end":0}]}]
for (int j=0; j < array.length(); j++)
{
try
{
JSONObject obj = array.getJSONObject(j);
String start = obj.getString("start");
String end = obj.getString("end");
Log.e("", "start = " + start);
}
catch (JSONException e)
{
Log.e("", "error = " + e.getMessage());
}
}
I get this error:
"error = No value for start"
Do this
JSONArray array = moduleObject.specialForcedConf;
// array = [{"deadlines":[{"start":1439539200,"end":1439542800},{"start":1440144000,"end":1440147600},{"start":0,"end":0}]}]
JSONArray jArray = array.getJSONObject(0).getJSONArray("deadlines");
for (int i = 0; i < jArray.length(); i++) // assuming your array is jArray
{
try
{
JSONObject obj = jArray.getJSONObject(i);
String start= obj.getString("start"); // store in an ArrayList
String end = obj.getString("end"); //// store in an ArrayList
}
catch (JSONException e)
{
// Error
}
}
JSONArray mJsonArray=new JSONArray("Deadlines");
for(int i=0;i<mJsonArray.length();i++){
JSONObject mJsonObject=new JSONObject(mJsonArray.get(i).toString));
String start = mJsonObject.optString("start","");
String end = mJsonObject.optString("end","");
}
Try this:
StringBuilder sb = new StringBuilder();
JSONArray arr = new JSONArray("deadlines");
for(int i=0;i<arr.length;i++){
JSONObject obj = arr.getJSONObject(i);
sb.append(obj.get("start").toString());
sb.append(",");
}
String strStartTag = sb;
JSONArray ja = new JSONArray(yourjsondata));
for (int i = 0; i < ja.length(); i++) {
JSONObject jo_feed = new JSONObject(ja.get(i).toString());
String start = jo_feed.getString("start");
}