Traverse array IN JSONArray - android

I'm making an app for android which makes a call to a webservice that returns a json with ARRAY as a parameter, I can go through all the settings and save them easily.
The problem is when I get the array that I returned within the JSON object.
Example of JSON:
[{"codigoArticulo":"0001","nombreArticulo":"CHULETAS DE CORDERO","factorVentasDefecto":"KG","precio":21.95,"factoresDeVenta":["KG","UN"]},{"codigoArticulo":"0007","nombreArticulo":"FALDETA DE CORDERO","factorVentasDefecto":"KG","precio":11.95,"factoresDeVenta":["KG","FL"]}]
I can save "codigoArticulo", "nombreArticulo", "factorVentasDefecto" and "precio easily, BUT i don't know how i can save "factoresDeVenta".
i have this code:
JSONArray resparray = new JSONArray(JSONdevuelto);
for (int i = 0; i < resparray.length(); i++) {
JSONObject respJSON = resparray.getJSONObject(i);
int IDArticulo = respJSON.getInt("codigoArticulo");
String NombreArticulo = respJSON.getString("nombreArticulo");
String FactordeVenta = respJSON.getString("factorVentasDefecto");
int PrecioArticulo = respJSON.getInt("precio");
}
How i can save in one array the variables on "factoresDeVenta"?
I try
String[] Factores = respJSON.getJSONArray("factoresDeVenta");
but no works because are incompatible types.
I need the array to make later a Spinner
Thank you.

factoresDeVenta is an JSONArray inside JSONObject so you will need to use getJSONArray or optJSONArray and use loop for getting values from JSONArray:
JSONArray jArray = respJSON.optJSONArray("factoresDeVenta");
for (int i = 0; i < jArray.length(); i++) {
String str_value=jArray.optString(i); //<< jget value from jArray
}

JSONArray jArray = respJSON.getJSONArray("factoresDeVenta");
It would give you the array of data stored in factoresDeVenta, which you can again traverse to get the individual elements from that array.

You can store in ArrayList<String>
ArrayList<String> arrStr = new ArrayList<String>();
JSONArray jArray = respJSON.optJSONArray("factoresDeVenta");
for (int i = 0; i < jArray.length(); i++) {
arrStr.add(jArray.getString(i));
}
And then you can convert arraylist to string array
String[] Factores = arrStr.toArray(new String[arrStr.size()]);

Related

Parsing json array with no arrayobject name in android

I want to parse the following data, everything is done but i'm confused at this last stage:
["ABC","DEF","GHI"]
How can I parse this type of json data?
Do it like this
JSONArray arr = new JSONArray(data); // assuming your json array is store in data
for(int i = 0; i < arr.length(); i++)
{
String str = arr.getString(i); // will return one string at a time
}

error while parsing an jsonarray

I am making a webservice call and the respond is in JSON.
The content which i get, is a JSONArray and looks like this:
{"jsonrpc":"2.0","id":"req-002","result":[
{"id":125043,"date":20110117,"startTime":800,"endTime":850,
"kl":[{"id":71}],"te":[{"id":23}],"su":[{"id":13}],"ro":[{"id":1}]},
{"id":125127,"date":20110117,"startTime":1055,"endTime":1145,
"kl":[{"id":71}],"te":[{"id":41}],"su":[{"id":19}],"ro":[{"id":31}]},
]}
Now i am trying to get the objects in the array, but i am only able to fetch the first array: for example i cant get the first "kl" array but i am not able to get the second one.
It always give me the error :
org.json.JSONException: Index 1 out of range [0..1)
This is what i have tried:
JSONObject jsonResult = new JSONObject(s);
// Get the result object
JSONArray arr = jsonResult.getJSONArray("result");
Log.d("Arraylänge", String.valueOf(arr.length()));
for(int i=0; i<arr.length(); i++){
JSONObject c = arr.getJSONObject(i);
anfangStunde[i] = c.getString("startTime");
endeStunde[i] = c.getString("endTime");
JSONArray klArr = c.getJSONArray("kl");
for(int j=0; i<klArr.length(); j++)
{
JSONObject k = klArr.getJSONObject(j);
klassenID[j] = k.getString("id");
}
You have a typo for(int j=0; **i**<klArr.length(); j++)

How to split this kind of data in android

Here is the
string one =[{"ID":5,"Name":"Sai"}]
how i get only id and name from this string
Matcher matcher = Pattern.compile("\\[([^\\]]+)").matcher(one);
List<String> tags = new ArrayList<String>();
int pos = -1;
while (matcher.find(pos+1)){
pos = matcher.start();
tags.add(matcher.group(1));
}
System.out.println("getting data"+tags);
i tried this but it didn't work
List<String> ls = new ArrayList<String>(one);
JSONArray array = new JSONArray();
for(int i = 0; i< array.length(); i++){
JSONObject obj = array.getJSONObject(i);
ls.add(obj.getString("Name"));
}
It's JSON format and it can very easily be read in Android. Here is the sample code:
JSONArray array = new JSONArray(one);
int length = array.length();
for(int i=0;i< length; i++)
{
JSONObject temp = array.getJSONObject(i);
System.out.println(temp.getString("ID"));
System.out.println(temp.getString("Name"));
}
This format of data is called JSON.
Have a look at Go to http://json.org/, scroll to (almost) the end, click on one of the many Java libraries listed.
First of all, your string initialization is wrong.
Wrong:
string one =[{"ID":5,"Name":"Sai"}]
Correct:
String one ="[{\"ID\":5,\"Name\":\"Sai\"}]";
Second, its a JSON formatted data so you can parse it using JSONArray and JSONObject classes, instead of creating any pattern.
Now, in your case its JSONObject inside JSONArray so initially create an object of JSONArray using your string.
For example:
JSONArray arrayJSON = new JSONArray(one); // 'one' is your JSON String
for(int i=0; i<arrayJSON.length(); i++) {
JSONObject objJson = arrayJSON.getJSONObject(i);
String ID = objJson.getString("ID");
.....
.....
// same way you can fetch/parse any string/value from JSONObject/JSONArray
}
it is a json formate Date
use JsonObject class to parse this data
tutorial this
JSONArray jsonArray = new JSONArray("[{\"ID\":5,\"Name\":\"Sai\"}]");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
System.out.println(object.getString("ID"));
System.out.println(object.getString("Name"));
}

Convert JSON string in array format into an array in java

I'm trying to take the following string that I got as a json object:
[
{
"id": "picture1",
"caption": "sample caption",
"picname": "sample picture name"
}
]
and turn it into a array so I can populate a list
I've tried turning it into a jsonarray by doing this:
JSONArray myjsonarray = myjson.toJSONArray(string_containing_json_above);
but that didn't seem to work.
==============
Here is full code with the working solution
myjson = new JSONObject(temp);
String String_that_should_be_array = myjson.getString("piclist");
JSONArray myjsonarray = new JSONArray(String_that_should_be_array);
For(int i = 0; i < myjsonarray.length(); i++){
JSONObject tempJSONobj = myjsonarray.getJSONObject(i);
showToast(tempJSONobj.get("caption").toString());
}
temp is the json from the server
Issue is here:
JSONArray myjsonarray = myjson.toJSONArray(temparray);
Solution:
JSONArray myjsonarray = new JSONArray(myJSON);
// myJSON is String
Now here you are having JSONArray, iterate over it and prepare ArrayList of whatever types of you want.
here you get JSONArray so change
JSONArray myjsonarray = myjson.toJSONArray(temparray);
line as shown below
JSONArray jsonArray = new JSONArray(readlocationFeed);
and after
JSONArray jsonArray = new JSONArray(readlocationFeed);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
explrObject.getString("caption");
}
JSONArray isn't working because the JSON you provided is not an array. You can read more about JSON syntax here: http://www.w3schools.com/json/json_syntax.asp
In the meantime, you could manually create your array by paring the JSON one string at a time.
JSONObject strings = new JSONObject(jsonString);
String array[] = new String[5];
if (jsonString.has("id"){
array[0] = jsonString.getString("id");
}
if (jsonString.has("caption"){
array[1] = jsonString.getString("caption");
}
...
etc.

Json data extracting in android

i want to extract the given json arry in android,
[{"Outofserviceday":{"outofservice":"2013-02-22"}},
{"Outofserviceday":{"outofservice":"2013-02-27"}},
{"Outofserviceday":{"outofservice":"2013-02-28"}}]
i have the code for extracting the json data like given below
[{"Requestcard":{"id":"994","userprofile_id":"14","userprofile_name":"Syed
Imran","company_name":"DLF Akruti Park, Hinjewadi, Pune,
Maharashtra","sex":"male","travel_date":"2013-02-12"}}]
in this case we can retrive the json boject using the code
JSONObject menuObject = json_data.getJSONObject("Requestcard");
and retrieve each element by
requestid= menuObject.getString("id");
But in the first case how we identify each Outofserviceday in the json array ? and How extract each data ???
you can do something like below, can create jsonArray from string json data and then can extracts json objects in a loop or so.
String json =" [{\"Outofserviceday\":{\"outofservice\":\"2013-02-22\"}}]"; //json-data which is basically a json array
JSONArray jArray = new JSONArray(json); / creating an jsonarray
for (int i = 0; i < jArray.length(); i++) {
// you can have jsonObject from json array here in the loop
}
Try this:
JSONObject json = new JSONObject(result);
JSONArray json1= json.getJSONArray("data");
if (json1.length()!=0) {
for (int i = 0; i < json1.length(); i++) {
String name = json1.getJSONObject(i).getString("name");
}
}
With the help of below code you can retrieve the value of outofservice
JSONArray jArray = new JSONArray(your data);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jOutOfServiceDay = jArray.getJSONObject(i);
JSONObject jobj = jOutOfServiceDay.getJSONObject("Outofserviceday");
Log.i("Required data is:", "" + jobj.getString("outofservice"));
}

Categories

Resources