I have an app where I fetch data from server(json) in the form of array & by using the index i used in my app, like below.
JSONObject topobj = new JSONObject(page);
JSONObject innerobj = topobj.getJSONObject("restarutant");
JSONArray phone = innerobj.getJSONArray("phone");
textViewPhone.setText("Phone: " + phone.get(0).toString() + " ,"
+ phone.get(1).toString());
for small size array I can get like this. But when array contains 'n' no of elements and dynamically i have to use this, at that time it required to convert into String Array.
Can anybody tell me how I convert the json array to String array ?
Thank you
This should help you.
Edit:
Maybe this is what you need:
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray jsonArray = new JSONArray();
for(int i = 0, count = jsonArray.length(); i< count; i++)
{
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
stringArray.add(jsonObject.toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
Assume that you already have JSONArray jsonArray:
String[] stringArray = new stringArray[jsonArray.length()];
for(int i = 0, count = jsonArray.length(); i< count; i++)
{
try {
String jsonString = jsonArray.getString(i);
stringArray[i] = jsonString.toString();
}
catch (JSONException e) {
e.printStackTrace();
}
}
This I think is what you searching for
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = (JSONArray)jsonObject;
if (jsonArray != null) {
for (int i=0;i<jsonArray.length();i++){
list.add(jsonArray.get(i).toString());
}
I just did this yesterday! If you're willing to use a 3rd party library then you can use Google GSON, with the additional benefit of having more concise code.
String json = jsonArray.toString();
Type collectionType = new TypeToken<Collection<String>>(){}.getType();
Collection<String> strings = gson.fromJson(json, collectionType);
for (String element : strings)
{
Log.d("TAG", "I'm doing stuff with: " + element);
}
You can find more examples in the user guide.
Another elegant kotlin way:
val list = jsonArray.map { jsonElement -> jsonElement.toString() }
And just convert to array if needed
If you are using org.json package, Here is the kotlin way of converting json array to string array.
// get json array
val jsonArray = json.getJSONArray("field")
// convert to string array
val stringArray = Array(jsonArray.length()) { jsonArray.getString(it) }
Related
I have a contacts which is in the form of JSON. Now I want to decode them into String array. There are two arrays; names and phones. I'm using this code:
String[] names;
String[] phones;
String test = "[{\"name\":\"A\",\"phone\":\"911\"},{\"name\":\"A1\",\"phone\":\"911\"},{\"name\":\"Abid\",\"phone\":\"371812\"}]";
try {
JSONArray jsonArray = new JSONArray(test);
JSONObject jsonObject = new JSONObject(jsonArray.toString());
Log.i("INFO", String.valueOf(jsonObject.length()));
} catch (JSONException e) {
e.printStackTrace();
}
This generates an error. How can I add all names in names array and all phones in phones array. Like names[0] is assigned A which is a first name and phones[0] assigned 911 which is first phone number corresponding to first name. How can I do that, I'm new in android?
The problem is in this line
JSONObject jsonObject = new JSONObject(jsonArray.toString());
you are trying to convert JSONArray in JSONObject , which you can't. if you want to access JSONObject inside of JSONArray you have to loop through each, or you can get specific object by it's index.
String[] names;
String[] phones;
String test = "[{\"name\":\"A\",\"phone\":\"911\"},{\"name\":\"A1\",\"phone\":\"911\"},{\"name\":\"Abid\",\"phone\":\"371812\"}]";
try {
JSONArray jsonArray = new JSONArray(test);
phones = names = new String[jsonArray.length()];
for(int i = 0 ; i < jsonArray.length(); i ++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
names[i] = jsonObject.getString("name");
phones[i] = jsonObject.getString("phone");
Log.i("INFO", "name : " + jsonObject.getString("name") + " , phone : " + jsonObject.getString("phone"));
}
} catch (JSONException e) {
e.printStackTrace();
}
You can't convert json arrya to json object like that:
try {
JSONArray jsonArray = new JSONArray(test);
for(int i=0; i<jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Your code goes here..
}
} catch (JSONException e) {
e.printStackTrace();
}
here is the required code.
ArrayList<String> names = new ArrayList<>();
ArrayList<String> phones = new ArrayList<>();
String test = "[{\"name\":\"A\",\"phone\":\"911\"},{\"name\":\"A1\",\"phone\":\"911\"},{\"name\":\"Abid\",\"phone\":\"371812\"}]";
try {
JSONArray jsonArray = new JSONArray(test);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name");
String phone = jsonObject.getString("phone");
names.add(name);
phones.add(phone);
Log.i("INFO", name + ", " + phone);
}
} catch (JSONException e) {
e.printStackTrace();
}
above you have used simple arrays they can store data only of fixed size. But arrayList and List can store data of variable size or you do not need to fix their size.
i want to get only gender but it shows {"face":[{"gender": {"value": "Male"}}]}
i only want gender
please help me how it solve JSONArray jArray = rst.getJSONArray("face");
for (int i = 0; i < jArray.length(); i++) {
String gender=jArray.getJSONObject(i).getJSONObject("attribute").getString("gender");
String jsonText;
jsonText = gender;
textview2.setText("GENDER" + jsonText);
Check this code:-
Case 1:This code generate only one toast
String result = "{\"face\":[{\"gender\": {\"value\": \"Male\"}}]} ";
try {
JSONArray objJsonArray = new JSONObject(result).getJSONArray("face");
String gender = new JSONObject(objJsonArray.getJSONObject(0).getString("gender")).getString("value");
Toast.makeText(this, "Gender is==>" + gender, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
Case 2:-This code generate two toasts.
String result = "{\"face\":[{\"gender\": {\"value\": \"Male\"}},{\"gender\": {\"value\": \"Female\"}}]}";
try {
JSONArray objJsonArray = new JSONObject(result).getJSONArray("face");
for (int i = 0; i < objJsonArray.length(); i++) {
String gender = new JSONObject(objJsonArray.getJSONObject(i).getString("gender")).getString("value");
Toast.makeText(this, "Gender is==>" + gender, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Hope it solves your problem
Try this on the last line:
textview2.setText("GENDER" + jsonText.value);
On this line you are getting the entire array:
JSONArray jArray = rst.getJSONArray("face");<br>
A JSONArray is an Array of json objects.
The json object is a name value pair.
It looks like this:
jArray[{name:”John” , gender:”male”},
{name:”jane” , gender:”female”},
{name:”Mike” , gender:”male”}]<br>
This next line loops through the array that you have. Each time pulling a different json object:
1st time through = [{name:”John” , gender:”male”}
2nd time through = {name:”jane” , gender:”female”}
3rd time through = {name:”Mike” , gender:”male”}
for (int i = 0; i < jArray.length(); i++) { String
On the first look i = 0
This following line is saying: retrieve the json data where the name is gender.
This returns {gender:”male”} “gender” being the name, “male” being the value.
gender=jArray.getJSONObject(i).getJSONObject("attribute").getString("gender").value; <br>
String jsonText; jsonText = gender;
textview2.setText("GENDER" + jsonText);
I believe there are other more efficient ways to handle this same code, but I hope this helps none the less.
try {
JSONObject jsonObject = new JSONObject(string);
JSONArray jsonArray = jsonObject.getJSONArray("face");
for(int i=0; i<jsonArray.length(); i++){
String gender = jsonArray.getJSONObject(i).getJSONObject("gender").getString("value");
}
} catch (JSONException e) {
e.printStackTrace();
}
if you have JsonArray length 1 then no need of for loop just replace i with 0
i have a json file like so :
http://da.pantoto.org/api/files
i want to store these values in variables to be used later. The values should be stored in some String array variables like id[], uploadDate[], url[].
i can find examples using ListView and ArrayAdapter. but thats not what i really want. Anyone can help??
This is only an example to show how you can get the values from JSON. You need to store these values as you need.
JSONObject jsonObject = new JSONObject("your response");
JSONArray filedetails = jsonObject.getJSONArray("files");
for(int i=0; i<filedetails.size();i++){
String id = filedetails.get(i).getString("id");
JSONArray tagsdetails= filedetails.get(i).getJSONArray("tags");
for(int i=0; i<tagsdetails.size();i++){
//fetch values in it
}
}
You can't do it exactly that way, You have to iterate trough the array and get each object properties individually and then if you want you could create an array to store each object property.
//From the example: http://da.pantoto.org/api/files
JSONArray files = null;
//Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
//Making a request to url and getting response
String jsonStr = sh.makeServiceCall("http://da.pantoto.org/api/files", ServiceHandler.GET);
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
files = jsonObj.getJSONArray("files");
//YOUR NEW ARRAY
String[] ids = new String[20];
String[] urls = new String[20];
//etc
//looping through All files
for (int i = 0; i < files.length(); i++) {
JSONObject c = files.getJSONObject(i);
String id = c.getString("id");
String url = c.getString("url");
//etc
//HERE IS WHAT YOU COULD DO OPTIONALLY IF YOU WANT HAVE IT ALL ON A SINGLE ARRAY WITHOUT OBJECTS:
ids[i] = id;
urls[i] = url;
//etc
}
this is a simple way to do this. see i also done this kind of string array and later use
try {
JSONObject jObj = new JSONObject(strDocketListResponse);
JSONArray jsonArray = jObj.getJSONArray("GetManifestDocketListResult");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject detailsObject = jsonArray.getJSONObject(i);
String strDktNo = detailsObject.getString("Docketno");
String strDocketDate = detailsObject.getString("DocketDate");
String strOrigin = detailsObject.getString("Origin");
String strDestination = detailsObject.getString("Destination");
String[] strDocketNoDkt = new String[]{strDktNo};
String[] strDocketDateDkt = new String[]{strDocketDate};
String[] strDocketOriginDkt = new String[]{strOrigin};
String[] strDocketDestnDkt = new String[]{strDestination};
for (int sanjay = 0; sanjay < strDocketNoDkt.length; sanjay++) {
ItemCheckList itemCheckList = new ItemCheckList();
itemCheckList.setDocket_NO(strDocketNoDkt[sanjay]);
itemCheckList.setDocket_Date(strDocketDateDkt[sanjay]);
itemCheckList.setDocket_Origin(strDocketOriginDkt[sanjay]);
itemCheckList.setDocket_Destination(strDocketDestnDkt[sanjay]);
checkLists.add(itemCheckList);
}
checkAdapter = new ItemCheckAdapter(ActivityManifestEntry.this, checkLists, check_all);
manifestListView.setAdapter(checkAdapter);
}
} catch (Exception e) {
e.printStackTrace();
}
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);
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);