Parse simple JSON Array without key - android

I need help with parsing simple JSONArray like this:
{
"text":[
"Morate popuniti polje tekst."
]
}
I have tried with this but I failed:
if (response_str != null) {
try {
JSONObject jsonObj = new JSONObject(response_str);
JSONArray arrayJson = jsonObj.getJSONArray("text");
for (int i = 0; i < arrayJson.length(); i++) {
JSONObject obj = arrayJson.optJSONObject(i);
error = obj.getString("text");
}
}

Your JSONArray is an array of Strings. You can iterate this way
JSONObject jsonObj = new JSONObject(response_str);
JSONArray arrayJson = jsonObj.getJSONArray("text");
for (int i = 0; i < arrayJson.length(); i++) {
String error = arrayJson.getString(i);
// Do something with each error here
}

You have a JSONArray text. There is no array of JSONObject.
{ // Json object node
"text":[ // json array text
"Morate popuniti polje tekst." // value
]
}
Just use
for (int i = 0; i < arrayJson.length(); i++) {
String value = arrayJson.get(i);
}
In fact there is no need for a loop as you have only 1 element in json array
You can just use
String value = (String) arrayJson.get(0); // index 0 . need to cast it to string
Or
String value = arrayJson.getString(0); // index 0
http://developer.android.com/reference/org/json/JSONArray.html
public Object get (int index)
Added in API level 1
Returns the value at index.
Throws
JSONException if this array has no value at index, or if that value is the null reference. This method returns normally if the value is JSONObject#NULL.
public boolean getBoolean (int index)
getString
public String getString (int index)
Added in API level 1
Returns the value at index if it exists, coercing it if necessary.
Throws
JSONException if no such value exists.

Try this:
JSONObject jsonObject = new JSONObject(response_str);
JSONArray arrayJson = jsonObject.getJSONArray("text");
String theString = arrayJson.getString(0);

Related

Get value from JSONArray

JSONObject obj looks like this:
{"data":"Text 1","data2":"Text 2","turnCounter":0,"data3":["0","1","2"]}
I have been able to retrieve data, data2, and turnCounter but I can't figure out how to get data3:
Here is my attempt
JSONObject obj = new JSONObject(st);
if (obj.has("data")) {
retVal.data = obj.getString("data"); //returns Text 1
}
if (obj.has("data2")) {
retVal.data2 = obj.getString("data2"); //returns Text 2
}
if (obj.has("turnCounter")) {
retVal.turnCounter = obj.getInt("turnCounter"); // returns 0
}
List<String> allNames = new ArrayList<String>();
JSONArray cast = obj.getJSONArray("data3");
for (int i=0; i<cast.length(); i++) { //does not return 0, 1, or 2
JSONObject data3 = cast.getJSONObject(i); //"" "" ""
retVal.data3.set(i, data3.toString()); //"" "" ""
}
Can someone please tell me how I can get the value from the JsonArray data3?
Please let me know if I need to provide more information.
The way to do it is:
JSONArray cast = obj.getJSONArray("data3");
String[] string_array = new String[]();
for (int i=0; i<cast.length(); i++) {
string_array[i] = cast.getString(i);
retVal.data3.set(i, string_array[i]);
}
Try this. This will work.
change
JSONObject data3 = cast.getJSONObject(i); //
to
String data3 = cast.getString(i);
The array contains strings so you should call getString(i) instead of getObject(i):
JSONArray cast = obj.getJSONArray("data3");
for (int i=0; i<cast.length(); i++) {
String data3 = cast.getString(i);
Log.e("TAG", data3);
}

How to convert the json array to string array in android?

I am converting an json array to string array thats doesn't exist any tag. I tried with all tricks but not succeeded.
json array:-
"validValues":["01_Abacus","02_AlarmClock","03_Basketball","04_Beaker","55_Watch"]
Code for convert the json array to string values
if (jsonComponentObj.has(TAG_VALID_VALUES)) {
String value = jsonComponentObj.getString(TAG_VALID_VALUES);
Logs.e("value " + value);
if (!value.equals("null")) {
JSONArray jsonArray = jsonComponentObj
.getJSONArray(TAG_VALID_VALUES);
if (jsonArray != null) {
ArrayList<String> stringArray = new ArrayList<String>();
for (int j = 0; j < jsonArray.length(); j++) {
try {
JSONObject jsonObject = jsonArray
.getJSONObject(j);
stringArray.add(jsonObject.toString());
} catch (JSONException e) {
Logs.e("Exception: "+e.toString());
e.printStackTrace();
}
}
}
}
}
Exception:
org.json.JSONException: Value 01_Abacus at 0 of type java.lang.String cannot be converted to JSONObject
If anyone have idea. Please reply. Thanks in advance..
Because validValues JSONArray contain only Strings instead of JSONObject.so get all values from JSONArray as:
for (int j = 0; j < jsonArray.length(); j++) {
String str_value = jsonArray.optString(j);
stringArray.add(str_value);
}
Your json array contains Strings not json object.Therefore to get Strings from json array directly use getString(),So
Change
JSONObject jsonObject = jsonArray.getJSONObject(j);
stringArray.add(jsonObject.toString());
to
stringArray.add(jsonArray.getString(j));
or
stringArray.add(jsonArray.optString(j));
You should use optString(int) to coerce a string value from array. Using getString(int) would cause problems if ever the values in the array were not strings.
for (int j = 0; j < jsonArray.length(); j++) {
String value = jsonArray.optString(j);
stringArray.add(value);
}
If you want to give a default value, use optString(int, String).
try JSONObject jsonObject = jsonArray.getString(j);
instead of JSONObject jsonObject = jsonArray.getJSONObject(j);

Parsing json array from the JSON object in 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;
}
//.....
}

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