Parsing json array from the JSON object in Android - android

I am trying to parse a JSON array from a string which I receive from the server.
Example of the array is
{"data":[{"id":703,"status":0,"number":"123456","name":"Art"}]}
I am trying to parse that using the below code which is giving me Classcast Exception which shows JSonArray can not be cast to List
JSONObject o = new JSONObject(result.toString());
JSONArray slideContent = (JSONArray) o.get("data");
Iterator i = ((List<NameValuePair>) slideContent).iterator();
while (i.hasNext()) {
JSONObject slide = (JSONObject) i.next();
int title = (Integer)slide.get("id");
String Status = (String)slide.get("status");
String name = (String)slide.get("name");
String number = (String)slide.get("number");
Log.v("ONMESSAGE", title + " " + Status + " " + name + " " + number);
// System.out.println(title);
}
What should be the correct way of parsing it?

It makes sense as a JSONArray cannot be cast to a List<>, nor does it have an iterator.
JSONArray has a length() property which returns its length, and has several get(int index) methods which allow you to retrieve the element in that position.
So, considering all these, you may wish to write something like this:
JSONObject o = new JSONObject(result.toString());
JSONArray slideContent = o.getJSONArray("data");
for(int i = 0 ; i < slideContent.length() ; i++) {
int title = slideContent.getInt("id");
String Status = slideContent.getString("status");
// Get your other values here
}

you should do like this:
JSONObject o = new JSONObject(result.toString());
JSONArray array = jsonObject.getJSONArray("data");
JSONObject jtemp ;
ArrayList<MData/*a sample class to store data details*/> dataArray= new ArrayList<MData>();
MData mData;
for(int i=0;i<array.length();i++)
{
mData = new MData();
jtemp = array.getJSONObject(i); //get i record of your array
//do some thing with this like
String id = jtemp.getString("id");
mData.setId(Integer.parseInt(id));
///and other details
dataArray.put(mData);
}
and MData.class
class MData{
private int id;
/....
public void setId(int id){
this.id = id;
}
//.....
}

Related

I want to list data from JSON string using an array, but why my app crashes?

I want to list data from a JSON string in ListView.
I store the strings in an array.
When I write i in the line JSONObject day = jsonArray.getJSONObject(0); the app crashes.
What did I wrong?
String json_string1 = "{\"list\":[{\"dt\":1471255200,\"temp\":{\"day\":30.04,\"min\":17.35,\"max\":30.04},\"pressure\":1018.83,\"humidity\":35,\"weather\":[{\"id\":802,\"main\":\"Clouds\",\"de scription\":\"scattered clouds\",\"icon\":\"03d\"}],\"speed\":2.66,\"deg\":314,\"clouds\":48},{\"dt\":1471341600,\"temp\":{\"day\":29.48,\"min\":19.3,\"max\":29.95},\"pressure\":1018.63,\"humidity\":100,\"weather\":[{\"id\":501,\"main\":\"Rain\",\"des cription\":\"moderate rain\",\"icon\":\"10d\"}],\"speed\":2.46,\"deg\":28,\"clouds\":92,\"rain\":8.5},{\"dt\":1471428000,\"temp\":{\"day\":28.96,\"min\":17.84,\"m ax\":297.54},\"pressure\":1012.1,\"humidity\":95,\"weather\":[{\"id\":501,\"main\":\"Ra in\",\"description\":\"moderate rain\",\"icon\":\"10d\"}],\"speed\":2.27,\"deg\":118,\"clouds\":88,\"rain\":5.55},{\"dt\":1471514400,\"temp\":{\"day\":26.89,\"min\":17.84,\" max\":28.95},\"pressure\":1014.27,\"humidity\":83,\"weather\":[{\"id\":500,\"main\":\"R ain\",\"description\":\"light rain\",\"icon\":\"10d\"}],\"speed\":1.98,\"deg\":93,\"clouds\":20},{\"dt\":1471600800,\"temp\":{\"day\":30.04,\"min\":21.87,\"max\":30.04},\"pressure\":1014.65,\"humidity\":0,\"weather\":[{\"id\":500,\"main\":\"Rain\",\"descrip tion\":\"light rain\",\"icon\":\"10d\"}],\"speed\":1.66,\"deg\":194,\"clouds\":11,\"rain\":0.22},{\"dt\":1471687200,\"temp\":{\"day\":31.3,\"min\":22.56,\"max\":32.3},\"p ressure\":1018.6,\"humidity\":0,\"weather\":[{\"id\":500,\"main\":\"Rain\",\"descriptio n\":\"light rain\",\"icon\":\"10d\"}],\"speed\":1.69,\"deg\":180,\"clouds\":16,\"rain\":0.77},{\"dt\":1471773600,\"temp\":{\"day\":31.77,\"min\":21.67,\"max\":30.77},\"pressure\":1016.93,\"humidity\":0,\"weather\":[{\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10d\"}],\"speed\":2.49,\"deg\":227,\"clouds\":14,\"rain\":2.2}]}";
JSONObject jsonObject;
String[] days_array = new String[7];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
jsonObject = new JSONObject(json_string1);
JSONArray jsonArray = jsonObject.optJSONArray("list");
int lengthJsonArr = jsonArray.length();
for (int i = 0; i < lengthJsonArr; i++) {
JSONObject day = jsonArray.getJSONObject(0);
JSONObject temp = day.getJSONObject("temp");
int min = temp.getInt("min");
int max = temp.getInt("max");
JSONArray weather = day.getJSONArray("weather");
JSONObject zero = weather.getJSONObject(0);
String main = zero.getString("main");
double speed = day.getDouble("speed");
days_array[i] = max + "/" + min + ", " + main + ", Wind=" + speed;
}
} catch (JSONException e) {
e.printStackTrace();
}
ListView ListView = (ListView) findViewById(R.id.list_view);
ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.list_layout, R.id.item_name, days_array);
ListView.setAdapter(adapter);
}
You had two wrong property names: "m ax" and " max". This fixed json will work:
String json_string1 = "{\"list\":[{\"dt\":1471255200,\"temp\":{\"day\":30.04,\"min\":17.35,\"max\":30.04},\"pressure\":1018.83,\"humidity\":35,\"weather\":[{\"id\":802,\"main\":\"Clouds\",\"de scription\":\"scattered clouds\",\"icon\":\"03d\"}],\"speed\":2.66,\"deg\":314,\"clouds\":48},{\"dt\":1471341600,\"temp\":{\"day\":29.48,\"min\":19.3,\"max\":29.95},\"pressure\":1018.63,\"humidity\":100,\"weather\":[{\"id\":501,\"main\":\"Rain\",\"des cription\":\"moderate rain\",\"icon\":\"10d\"}],\"speed\":2.46,\"deg\":28,\"clouds\":92,\"rain\":8.5},{\"dt\":1471428000,\"temp\":{\"day\":28.96,\"min\":17.84,\"max\":297.54},\"pressure\":1012.1,\"humidity\":95,\"weather\":[{\"id\":501,\"main\":\"Ra in\",\"description\":\"moderate rain\",\"icon\":\"10d\"}],\"speed\":2.27,\"deg\":118,\"clouds\":88,\"rain\":5.55},{\"dt\":1471514400,\"temp\":{\"day\":26.89,\"min\":17.84,\"max\":28.95},\"pressure\":1014.27,\"humidity\":83,\"weather\":[{\"id\":500,\"main\":\"R ain\",\"description\":\"light rain\",\"icon\":\"10d\"}],\"speed\":1.98,\"deg\":93,\"clouds\":20},{\"dt\":1471600800,\"temp\":{\"day\":30.04,\"min\":21.87,\"max\":30.04},\"pressure\":1014.65,\"humidity\":0,\"weather\":[{\"id\":500,\"main\":\"Rain\",\"descrip tion\":\"light rain\",\"icon\":\"10d\"}],\"speed\":1.66,\"deg\":194,\"clouds\":11,\"rain\":0.22},{\"dt\":1471687200,\"temp\":{\"day\":31.3,\"min\":22.56,\"max\":32.3},\"p ressure\":1018.6,\"humidity\":0,\"weather\":[{\"id\":500,\"main\":\"Rain\",\"descriptio n\":\"light rain\",\"icon\":\"10d\"}],\"speed\":1.69,\"deg\":180,\"clouds\":16,\"rain\":0.77},{\"dt\":1471773600,\"temp\":{\"day\":31.77,\"min\":21.67,\"max\":30.77},\"pressure\":1016.93,\"humidity\":0,\"weather\":[{\"id\":500,\"main\":\"Rain\",\"description\":\"light rain\",\"icon\":\"10d\"}],\"speed\":2.49,\"deg\":227,\"clouds\":14,\"rain\":2.2}]}";
To ensure that it does not happen again, you can use online tools such as the next https://jsoneditoronline.org/ to validate your future jsons before thinking that you have any error in your code.
One more thing, you could also improve the name of your variable String json_string1 byString jsonString1 to keep java's camel case convention

Convert JSONArray string value into int value

I need to convert the value from key "Quantity" into a int.
Basically I have this:
[{"Code":"NV","Quantity":"333"},{"Code":"NV","Quantity":"333"}]
Need to convert to this:
[{"Code":"NV","Quantity":333},{"Codigo":"NV","Quantity":333}]
How can I do it?
Assuming your json data in string and setting it in data string
String data = "[{\"Code\":\"NV\",\"Quantity\":\"333\"},{\"Code\":\"NV\",\"Quantity\":\"333\"}]";
try {
JSONArray jsonArray = new JSONArray(data);
Log.d(TAG, "Old JSONArray: " + jsonArray); // [{"Code":"NV","Quantity":"333"},{"Code":"NV","Quantity":"333"}]
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
int quantityValue = Integer.parseInt(jsonObject.getString("Quantity"));
jsonObject.put("Quantity", quantityValue);
}
Log.d(TAG, "New JSONArray: " + jsonArray); // [{"Code":"NV","Quantity":333},{"Code":"NV","Quantity":333}]
} catch (JSONException e) {
e.printStackTrace();
}
What I am doing here is just replacing old Quantity string value with int value by using Integer.parseInt()
Please try the following:
for(int i = 0; i < array.length(); i++){
JSONObject object = array.getJSONObject(i);
object.put("Quantity", Integer.parseInt(object.getString("Quantity")));
}
You will need to replace array with the name of your array.

How to parse this JSON in to string in android?

Can someone show me how to write this json into a code?
Is it correct if I get this json data as json object first and the loop the jsonarray in the try catch block in android?
{"charges":[{"Fhour":"0.3","Shour":"0.2","Rhours":"0.1"}]}
Kindly help me thanks in advance
Your String can be parsed like
String json = "{\"charges\":[{\"Fhour\":\"0.3\",\"Shour\":\"0.2\",\"Rhours\":\"0.1\"}]}";
JSONObject jsonObject = new JSONObject(json);
JSONArray charges = jsonObject.getJSONArray("charges");
for (int i = 0; i < charges.length(); i++) {
JSONObject c = charges.get(i);
String fHour = c.getString("Fhour");
String sHour = c.getString("Shour");
String rHours = c.getString("Rhours");
Log.d("(f,s,r)Hours : ", "(" + fHour + "," + sHour + "," + rHours + ")");
}
Use built-in JSON library.
JSONObject buddiesDoc = new JSONObject(result);
JSONArray buddies = buddiesDoc.getJSONArray("buddies");
for (int n = 0; n < buddies.length(); n++) {
JSONObject object = buddies.getJSONObject(n);
object.getString(BuddyManager.CACHED_BUDDY_KEY_CONTACTID);
...

Not getting values from json in android

I am trying to parse my json with:
for(int i = 0; i < json.getJSONArray("JSON").length(); i++) {
String taste = json.getJSONArray("JSON").getJSONObject(i).getString("taste");
String rate = json.getJSONArray("JSON").getJSONObject(i).getString("rate");
int foo = Integer.parseInt(rate);
count = count + foo;
//create object
BeerTastes tempTaste = new BeerTastes(taste, rate);
//add to arraylist
tasteList.add(tempTaste);
Log.d("taste",tempTaste.taste);
Log.d("number",tempTaste.percent);
}
But my logs at the end are not outputting anything at all so I assume I am not parsing my json correctly. The json I am looking at is:
[{"taste":"Bitter","rate":"13"},{"taste":"Malty","rate":"3"},{"taste":"Smooth","rate":"3"},{"taste":"Dry","rate":"1"}]
I think I may be wrong with:
json.getJSONArray("JSON")
because my array doesnt have a name but I it has to take a string...
I find no 'JSON' in your JSON String.So i think you should write like this:
JSONArray jsonArray = new JSONArray(json);
then:
for(int i = 0; i < jsonArray.length(); i++) {
String taste = jsonArray.getJSONObject(i).getString("taste");
String rate = jsonArray.getJSONObject(i).getString("rate");
int foo = Integer.parseInt(rate);
count = count + foo;
//create object
BeerTastes tempTaste = new BeerTastes(taste, rate);
//add to arraylist
tasteList.add(tempTaste);
Log.d("taste",tempTaste.taste);
Log.d("number",tempTaste.percent);
}

How to add values to a string array in android

I have a problem with my code,
I have a json array
[{"Response":{"data":"sibin1"}},{"Response":{"data":"sibin2"}},
{"Response": {"data":"sibin3"}}]
And iam trying to extract the json data using the below code,Here i added only some parts of the coode
JSONArray finalResult = new JSONArray(tokener);
int finalresultlengt=finalResult.length();
JSONObject json_data = new JSONObject();
for (int i = 0; i < finalResult.length(); i++)
{
json_data = finalResult.getJSONObject(i);
System.out.println("json dataa"+json_data.names().toString());
JSONObject menuObject = json_data.getJSONObject("Response");
result= menuObject.getString("data");
System.out.println(result);
}
The code is worked very well
when the value of
i=0 ,result is sibin1
i=1 ,result is sibin2
i=2 ,result is sibin3
But my problem is , i need to store the result in a string array of length finalresultlength inside the given for loop, also i need to print the values in the string array in a for loop outside the given for loop
if anybody knows please help me...........
You could do this way as well.
Create an ArrayList of size 'finalresultlengt' and the add the values in.
list.add(result); // variable 'result' in your case is the value from JSON
If you have more values to be added, create a POJO class.
class POJO {
private String dataVal;
public void setDataVal(String dataVal) {
this.dataVal = dataVal;
}
public String getDataVal() {
return dataVal;
}
}
Then create an ArrayList of type POJO.
ArrayList<POJO> list = new ArrayList<POJO>(finalresultlengt);
EDIT
JSONArray finalResult = new JSONArray(tokener);
int finalresultlengt=finalResult.length();
JSONObject json_data = new JSONObject();
ArrayList<String> list = new ArrayList<String>(finalresultlengt);
for (int i = 0; i < finalResult.length(); i++) {
json_data = finalResult.getJSONObject(i);
System.out.println("json dataa"+json_data.names().toString());
JSONObject menuObject = json_data.getJSONObject("Response");
result= menuObject.getString("data");
list.add(result);
}
Populate values from ArrayList.
for(String value : list)
System.out.println(value);

Categories

Resources