Not getting values from json in android - 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);
}

Related

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 store json values in a set of arrays in android

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

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

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

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