How to get maximum/largest value from json object with Android? - 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);

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

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.

Read JSON array without curly brackets

I'm trying to get the values from array in a JSON file. Array only has a square brackets and not curly brackets something like this:
"{"name_of_the_array: ["value_1", "value_2"]"}"
I found here some answer but it did not work for me the code of the answer is:
JSONArray array = new JSONArray("array_name");
for (int i = 0; i < array.length(); i++) {
str = array.get(i).toString();
list.add(str);
}
the list is ArrayList list.
{} denotes a JSONObject so you have to create a JSONObject first. [] denotes a JSONArray. You have to fetch the JSONArray from JSONObject with key.
Use this code
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray array = jsonObject.getJSONArray("array_name");
for (int i = 0; i < array.length(); i++) {
str = array.get(i).toString();
list.add(str);
}
Check this and this for parsing
try something like this
JSONArray array = new JSONArray("array_name");
for (int i = 0; i < array.length(); i++) {
str = array.getJSONObject(i).getString("string_name");
list.add(str);
}
or you can try this too
JSONArray array = new JSONArray("array_name");
for (int i = 0; i < array.length(); i++) {
str = array.getString("string_name");
list.add(str);
}

how to get json which has multiple values in a string in android

I have a json which has multiple values separated by commas which is in the
form of array.I want to get skills and platforms string separately.Can you please help me?
I want to show skills string and platforms string in text.
Please help me.
The format is:
{
"data": [
{
"skills": "ANDROID SDK, ANIMATION, ANGULARJS,",
"platforms": "IOS Application, Social Networking, Online shopping Sites, Web Application"
}
],
"status": 100
}
Try this one
try {
JSONObject ob = new JSONObject(response);
int status = ob.getInt("status");
if (status == 100) {
JSONArray ja = ob.getJSONArray("data");
for (int i = 0; i < ja.length(); i++) {
values = new HashMap<>();
JSONObject vj = ja.getJSONObject(i);
String skills = vj.getString("skills "));
String platforms=vj.getString("platforms"));
data.add(values);
}
split these 2 strings using 'split()'
List<String> skillsArray = Arrays.asList(skills.split(","));
List<String> platformsArray= Arrays.asList(platforms.split(","));
String in = "your json";
JSONObject jsonObj = new JSONObject(in);
// Getting JSON Array node
JSONArray jsonarray = jsonObj.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String skills = jsonobject.getString("skills");
String platforms = jsonobject.getString("platforms");
}
Try this
JSONObject jsonObject = new JSONObject("Your json response");
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonobject = jsonArray.getJSONObject(i);
String skill = jsonobject.getString("skills");
String platforms = jsonobject.getString("platforms");
String[] skillsArray = skill.split(Pattern.quote(","));
String[] platformsArray = platforms.split(Pattern.quote(","));
for (int j=0; j<skillsArray.length; j++)
{
Log.i("Skill Value ", "=" + skillsArray[j]);
}
for (int j=0; j<platformsArray.length; j++)
{
Log.i("platforms Value ", "=" + platformsArray[j]);
}
}
Output
First of all convert your output string into json. Note that output string is the string which contains your results of json format that you have posted above.following is the code on how to do that:
JSONObject myJsonResponse = new JSONObject(yourString);
The next one is Array. That is how you will get it and will iterate over it.
JSONArray jsonarray = jsonObj.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject innerJsonObject= jsonarray.getJSONObject(i);
String skills = innerJsonObject.getString("skills");
String platforms = innerJsonObject.getString("platforms");
}
Now you have gotten your required fields and you can now perform any String functions over the String skills and platforms.
Happy coding. .
The best way is creating a model class such :
public class MyModel{
Properties [] data;
class Properties{
public String skills;
public String platforms;
}
}
then you can parse your string to model with Gson library like this :
MyModel myModel = new Gson().fromJson(yourString, MyModel.class)
so all data is in myModel object and you can access to skills with
myModel.data[0].skills
to add Gson library to your project add below to your app gradle file :
compile 'com.google.code.gson:gson:2.8.1'
You may try this,
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject("JSON_STRING");
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonobject = jsonArray.getJSONObject(i);
String skills = jsonobject.getString("skills");
String[] seperateData = skills.split(Pattern.quote(","));
for (int j = 0; j < seperateData.length; j++) {
Log.e("Your Skill Value-> ", seperateData[j]);
}
String platforms = jsonobject.getString("platforms");
seperateData = platforms.split(Pattern.quote(","));
for (int j = 0; j < seperateData.length; j++) {
Log.e("Your Platform Value-> ", seperateData[j]);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
class Data{
public String skills;
public String platforms;
}
Gson gson = new Gson();
JSONArray dataArray = response.getJSONArray("data");
List<Data> dataList= gson.fromJson(dataArray toString(), new TypeToken<List<Data>>() {
}.getType());
Try this.. It will make parsing easier.
implementation 'com.google.code.gson:gson:2.8.0'
First Parse your JSON:
JSONObject jsonObj = new JSONObject(in);
JSONArray jsonarray = jsonObj.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String skills = jsonobject.getString("skills");
String platforms = jsonobject.getString("platforms");
}
Then Split your string values:
String skills = "ANDROID SDK, ANIMATION, ANGULARJS";
String[] separated = CurrentString.split(",");
separated[0]; // this will contain "ANDROID SDK"
separated[1]; // this will contain " ANIMATION"
separated[2]; // this will contain " ANGULARJS"
You have to remove the space to the second String:
separated[1] = separated[1].trim();
Try this you will be getting all values of sapereted with commas
jsonString = getting string from server side
String[] separated = jsonString.split(",");
StringBuilder s = new StringBuilder(10000);
for (int i = 0; i < separated.length; i++) {
if (i == separated.length - 1) {
s.append(separated[i].trim() + "");
} else {
s.append(separated[i].trim() + ",\n");
}
}
//tvDisplayAddress.setText(s);
Log.e("VALUES: ",s+"");

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

Categories

Resources