Convert JSONArray string value into int value - android

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.

Related

Android Studio: of type org.json.JSONObject cannot be converted to JSONArray

I get error: of type org.json.JSONObject cannot be converted to JSONArray when I try to retrieve JSON values.
JSONArray jsonarray = new JSONArray(data);
for(int i = 0; i < jsonarray.length(); i++){
JSONObject JO = (JSONObject) jsonarray.get(i);
String id = JO.getString("languages");
dataParsed = dataParsed + id;
}
The JSON looks like this (have removed sensitive data)
{
"ip":"",
"type":"",
"continent_code":"EU",
"continent_name":"Europe",
"country_code":"GB",
"country_name":"United Kingdom",
"region_code":"ENG",
"region_name":"England",
"city":"",
"zip":"",
"latitude":,
"longitude":,
"location":{
"geoname_id":,
"capital":"London",
"languages":[
{
"code":"en",
"name":"English",
"native":"English"
}
],
"country_flag":"http:\/\/assets.ipstack.com\/flags\/gb.svg",
"country_flag_emoji":"\ud83c\uddec\ud83c\udde7",
"country_flag_emoji_unicode":"U+1F1EC U+1F1E7",
"calling_code":"44",
"is_eu":true
}
}
I should mention that the data I actually want to retrieve is the name of the language.
You could try this:
JSONObject obj = new JSONObject(data);
JSONObject objLocation = obj.getJSONObject("location");
JSONArray arrayLanguage = objLocation.getJSONArray("languages");
for (int i = 0; i < arrayLanguage.length(); i++) {
JSONObject JO = (JSONObject) arrayLanguage.get(i);
String id = JO.getString("languages");
dataParsed = dataParsed + id;
}

Decode JSON String in 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.

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

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

How to get maximum/largest value from json object with Android?

I've json string like this:
{"GetReportResult":[
{"bulan":"4","total":"2448","type":"CHEESE1K","uang":"8847823"},{"bulan":"4","total":"572476","type":"ESL","uang":"5863408410"},{"bulan":"4","total":"46008","type":"ESL500ML","uang":"234498301"},{"bulan":"4","total":"228985","type":"UHT","uang":"1367172990"},{"bulan":"4","total":"40995","type":"WHP","uang":"235750452"},{"bulan":"5","total":"5703","type":"CHEESE1K","uang":"134929306"},{"bulan":"5","total":"648663","type":"ESL","uang":"6645764498"},{"bulan":"5","total":"49305","type":"ESL500ML","uang":"266817346"},{"bulan":"5","total":"287867","type":"UHT","uang":"1446897805"},{"bulan":"5","total":"51958","type":"WHP","uang":"631994613"},{"bulan":"6","total":"4390","type":"CHEESE1K","uang":"104527773"},{"bulan":"6","total":"443335","type":"ESL","uang":"4540123082"},{"bulan":"6","total":"28462","type":"ESL500ML","uang":"148290912"},{"bulan":"6","total":"213250","type":"UHT","uang":"1197646870"},{"bulan":"6","total":"27049","type":"WHP","uang":"189802525"}
]}
I want to get maximum/largest value of bulan, which is 6. How to do that on android?
This should do it.
JSONObject json = new JSONObject("your json string");
JSONArray jsonArray = json.getJSONArray("GetReportResult");
int max = -1;
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject temp = jsonArray.getJSONObject(i);
if(temp.getInt("bulan") > max)
max = temp.getInt("bulan");
}
Log.e("Max", "" + max);

Categories

Resources