Decode JSON String in Android - android

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.

Related

same number is giving output for mobile_number string

Hi in the below code below mobile is
mobile:["9841910799","04651226127","9639355527","04428213134","8939597777","04428223060","04428311001","9822363585","8318043412","9919588852","9919588852","9919588852","9828722750","8875518030","9862145100","9414135437","9414135437"]
String mobile=sharedPreferences.getString("mobile",null);
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(mobile);
String[] strArr = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
strArr[i] = jsonArray.getString(i);
mobile_number1= String.valueOf(strArr[i]);
for(int j=0;j<mobile_number1.length();j++){
mobile_number= String.valueOf(mobile_number1.toCharArray());
}
}
} catch (JSONException e) {
e.printStackTrace();
}
For every time I am getting the single number
expected output
mobile_number=9841910799
9841910797
etc
Try bellow updated code
String mobile=sharedPreferences.getString("mobile",null);
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(mobile);
String[] strArr = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
strArr[i] = jsonArray.getString(i);
mobile_number1= String.valueOf(strArr[i]);
for(int j=0;j<mobile_number1.length();j++){
mobile_number=mobile_number+ String.valueOf(mobile_number1.toCharArray());
}
}
} catch (JSONException e) {
e.printStackTrace();
}
As per my understanding the problem, you are assigning value every time as the new in mobile_number variable, not assigning previous plus new number.

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.

I am getting error as value of java.lang.String cannot be converted to JSONObject [duplicate]

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
my JSONResponse looks as follows
[["1","somevalue","1234567890","1239876093","some"], ["2","somevalue","1234567890","1234567890","some"]]
and code accessing it is as follows
try{
String[] details = {""};
JSONArray array1 = new JSONArray(response);
JSONArray array = array1.getJSONArray(0);
JSONObject object;
//print(array.length() + "");
for(int i = 0; i < array.length(); i++){
object = array.getJSONObject(i);
details[i] = object.getString("roll") + " " + object.getString("name");
ArrayList<String> list = new ArrayList<>();
list.addAll(Arrays.asList(details));
ArrayAdapter<String> defaulters = new ArrayAdapter<String>(ShowDefaulters.this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(defaulters);
}
}
catch (Exception e){
print(e.getMessage());
}
You must get jsonarray on object array. example:
private void test(){
String json_text ="[[\"1\",\"somevalue\",\"1234567890\",\"1239876093\",\"some\"], [\"2\",\"somevalue\",\"1234567890\",\"1234567890\",\"some\"]]";
try{
JSONArray array1 = new JSONArray(json_text);
JSONArray array = array1.getJSONArray(0);
Log.e("ARR", array.toString());
JSONArray user_arr = new JSONArray(array.toString());
for(int i=0; i< user_arr.length(); i++){
Log.e("USER", user_arr.get(i).toString());
}
}
catch (Exception e){
Log.e("ERROR", e.getMessage());
}
}
or:
private void test(){
String json_text ="[[\"1\",\"somevalue\",\"1234567890\",\"1239876093\",\"some\"], [\"2\",\"somevalue\",\"1234567890\",\"1234567890\",\"some\"]]";
try{
JSONArray array1 = new JSONArray(json_text);
JSONArray array = array1.getJSONArray(0);
Log.e("ARR", array.toString());
JSONArray user_arr = new JSONArray(array.toString());
Log.e("USER", "roll: " + user_arr.get(0).toString());
Log.e("USER", "name: " + user_arr.get(1).toString());
}
catch (Exception e){
Log.e("ERROR", e.getMessage());
}
}

not getting the specific result json object and how to compare the two string's

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

android how to convert json array to string array

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) }

Categories

Resources