Store json array keys data in separate arrayLists - android

I have this kind of json data returning from url as shown in Image1 Image2 Image3
Basically there are dates inside data and then within these dates there are further 5 different things i.e. session_from, session_to, rate, bookingFound and promotion. What i want is that i want to store all these dates data in separate arraylist.
For example:
sessionfrom0 contains data for 09-09-2018 and all its objects
sessionfrom1 contains data for 10-09-2018 and all its objects
sessionfrom2 contains data for 11-09-2018 and all its objects
I have tried with following piece of code but its not working correctly
JSONObject jsonObject = new JSONObject(response);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
sessionsfrom0 = new ArrayList<String>();
sessionsfrom1 = new ArrayList<String>();
sessionsfrom2 = new ArrayList<String>();
while (iter.hasNext()) {
key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
for (int i = 0; i < datesArray.length(); i++) {
JSONObject datesObject0 = datesArray.getJSONObject(i);
JSONObject datesObject1 = datesArray.getJSONObject(i);
JSONObject datesObject2 = datesArray.getJSONObject(i);
sessionsfrom0.add(datesObject0.getString("session_from") + " - " +datesObject0.getString("session_to");
sessionsfrom1.add(datesObject1.getString("session_from") + " - " +datesObject1.getString("session_to");
sessionsfrom2.add(datesObject2.getString("session_from") + " - " +datesObject2.getString("session_to");
} }
This code not working correctly, as you can see that date 09-09-2018 contains further array of size 4 and and in those array there are further 5 items inside each jjson object so i want to store all this in first arraylist i.e. sessionfrom0 and then go to next date and pick all its arrays and json objects and store data in sessionfrom1 arraylist and so on.

Try this:
JSONObject jsonObject = new JSONObject(response);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
sessionsfrom0 = new ArrayList<String>();
sessionsfrom1 = new ArrayList<String>();
sessionsfrom2 = new ArrayList<String>();
while (iter.hasNext()) {
String key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
switch (key) {
case "2018-09-09":
fillSessions(datesArray, sessionsfrom0);
break;
case "2018-10-09":
fillSessions(datesArray, sessionsfrom1);
break;
....so on....
}
}
You can create a function instead of rewriting the for loop logic on each case:
void fillSessions(JSONArray jsonArray, List<String> sessionList) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject datesObject = jsonArray.getJSONObject(i);
sessionList.add(datesObject.getString("session_from") + " - " +datesObject0.getString("session_to");
}
}

You can do this by using HashMap
JSONObject jsonObject = new JSONObject(response);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
HashMap<String, ArrayList<String>> map = new HashMap<>();
while (iter.hasNext()) {
key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < datesArray.length(); i++) {
JSONObject datesObject0 = datesArray.getJSONObject(i);
list.add(datesObject0.getString("session_from") + " - " + datesObject0.getString("session_to");
}
map.put(key, list);
}

Try this:
JSONObject jsonObject = new JSONObject(response);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
Map<String, ArrayList<String>> map = new TreeMap<>();
while (iter.hasNext()) {
String key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
ArrayList<String> tmp = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject datesObject = jsonArray.getJSONObject(i);
tmp.add(datesObject.getString("session_from") + " - "+datesObject.getString("session_to"));
}
map.put(key, tmp);
}
Probably you don't have all keys inside data so using switch case is not sensitive.

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

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

Android get elements from json array

I'm trying to get elements from my json array.
this is my json response:
{"IDs":["635426812801493839","635429094450867472","635433640807558204"]}
This is what I've tried so far:
itemList = new ArrayList<HashMap<String, String>>();
JSONArray a = jsonObj.getJSONArray(Constants.IDS);
int arrSize = a.length();
ArrayList<String> stringArray = new ArrayList<String>();
for (int i = 0; i < arrSize; ++i) {
JSONObject obj = a.getJSONObject(i);
stringArray.add(obj.toString());
item = new HashMap<String, String>();
item.put(Constants.ID, obj.toString());
itemList.add(item);
}
Log.e("ARR COUNT", "" + stringArray.size());
But I'm getting empty list. What is wrong with my code? Any help will be truly appreciated. Thanks.
The for loop should be
for (int i = 0; i < arrSize; ++i) {
stringArray.add(a.getString(i));
your the JSONArray contains already string
JSONObject obj = a.getJSONObject(i);
replace with
String str = a.getString(i);
Use this
itemList = new ArrayList<HashMap<String, String>>();
JSONArray a = jsonObj.getJSONArray(Constants.IDS);
int arrSize = a.length();
ArrayList<String> stringArray = new ArrayList<String>();
for (int i = 0; i < arrSize; ++i) {
stringArray.add(a.getString(i));
item = new HashMap<String, String>();
item.put(Constants.ID, obj.toString());
itemList.add(item);
}
Log.e("ARR COUNT", "" + stringArray.size());

at 0 of type org.json.JSONArray cannot be converted to JSONObject

I have values stored in the JSON url and parsing the value from json then displaying in the app.I'm using Async task to get the values from JSONArray and display in the list. when i get the values from server i got error and the json values are
[{"name":"John","uuid":"B9407F30-F5F8-466E-AFF9-25556B57FE6D","major_id":"67889","minor_id":"7032","notification":"Welcome","type":"Website","website":"estimote.com"}]
Log:
10-16 17:46:38.996: W/System.err(11224): org.json.JSONException: Value [{"notification":"Welcome","uuid":"B9407F30-F5F8-466E-AFF9-25556B57FE6D","type":"Website","website":"estimote.com","major_id":"67889","minor_id":"7032","name":"John"}] at 0 of type org.json.JSONArray cannot be converted to JSONObject
10-16 17:46:38.996: W/System.err(11224): at org.json.JSON.typeMismatch(JSON.java:100)
10-16 17:46:38.996: W/System.err(11224): at org.json.JSONArray.getJSONObject(JSONArray.java:484)
code:
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
//JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray jarray = new JSONArray(jsonStr);
jObject = jarray.getJSONObject(0);
Log.d("jsonObj_Response: ", "> " + jarray);
// Getting JSON Array node
contacts = jObject.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
//TAG_ID, TAG_NAME, TAG_major_id, TAG_minor_id, TAG_notification, TAG_type
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_major_id);
String address = c.getString(TAG_minor_id);
String gender = c.getString(TAG_notification);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_major_id, email);
contact.put(TAG_minor_id, address);
// adding contact to contact list
contactList.add(contact);
}
you missed a JSONArray
JSONArray jarray = new JSONArray(jsonStr);
for (int i = 0; i < jarray.length(); i++) {
JSONArray innerArray = jarray.optJSONArray(i);
for (int j = 0; j < innerArray.length(); j++) {
jObject = innerArray.getJSONObject(j);
}
}
After OP's Edit
JSONArray jarray = new JSONArray(jsonStr);
for (int i = 0; i < jarray.length(); i++) {
JSONObject jobj = jarray.optJSONObject(i);
if (jobj != null) {
}
}
jObject = jarray.getJSONObject(0) is a JSONArray, your string has an object within an array within an array ;)
You have two arrays ("[["/"]]") so "jObject = jarray.getJSONObject(0);" fails as it tries to convert "[{"name" ... estimote.com"}]" to a JSONObject but this is a JSONArray.
jarray[0] is a JSONarray not a JSONObject.
My soluation as follows ,
JSONArray arr = new JSONArray(jsonStr);//Response string is here
for (int i = 0; i < arr.length(); i++) {
JSONArray arr2 = arr.optJSONArray(i);
for (int j = 0; j < arr2.length(); j++) {
jObject = arr2.getJSONObject(0);
}
}

How to set json data to list view?

I tried to add json data to listview.But i don't know how to add the json data to list adapter.
try {
mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("restaurants");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("name");
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
if(restName.equalsIgnoreCase(name)){//this name is predefined name.
String address = jsonChildNode.optString("address");
String mobile = jsonChildNode.optString("mobile");
String direction = "Direction: "+jsonChildNode.optString("direction");
String bestTime = "Best time to visite: "+jsonChildNode.optString("bestTime");
String food = jsonChildNode.optString("food");
String dress = jsonChildNode.optString("dress");
String priceRange = "Price Range: "+jsonChildNode.optString("priceRange");
String rate = jsonChildNode.optString("Rate");
String comment = "Price Range: "+jsonChildNode.optString("comment");
map.put("restName",restName);
map.put("address",address);
map.put("mobile",mobile);
map.put("direction",direction);
map.put("bestTime",bestTime);
map.put("food",food);
map.put("dress",dress);
map.put("priceRange",priceRange);
map.put("rate",rate);
map.put("comment",comment);
mylist = new ArrayList<HashMap<String, String>>();
mylist.add(map);
}else{
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
// ListAdapter adapter = new SimpleAdapter(getApplicationContext(),android.R.layout.simple_list_item_1,mylist);
// list.setAdapter(adapter);
}
Can anyone tel me how to set this data to list view.?
Try this..
Your doing reversely. declear the arraylist before for loop and declear the HashMap inside the for loop .
mylist = new ArrayList<HashMap<String, String>>();
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("restaurants");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("name");
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
if(restName.equalsIgnoreCase(name)){//this name is predefined name.
HashMap<String, String> map = new HashMap<String, String>();
String address = jsonChildNode.optString("address");
//So on
map.put("restName",restName);
//So on
mylist.add(map);
}else{
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
}
google-gson
I would use gson for this. Check the gson project website for more details on how. This is an example for object serialisation/deserialisation:
Object Examples
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);
==> json is {"value1":1,"value2":"abc"}
Note that you can not serialize objects with circular references since that will result in infinite recursion.
(Deserialization)
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
==> obj2 is just like obj

Categories

Resources