Unable to get JSON values separately in Android - android

I have a trouble finding a way how to parse JSONArray
This is my JSON:
{
"result": [
[
"id",
"name",
"origin",
"destination"
],
[
1,
"A S Peta",
0,
0
],
[
2,
"Aachara",
0,
0
],
.
.
.
[
2238,
"sydney",
0,
0
]
]
}
I need to access it in Android app. I have tried and I am able to receive values, but they are displaying in a single row, and I am unable to split the fields.
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("result");
for (int i = 1; i < contacts.length(); i++) {
String name = contacts.getString(i).replaceAll("\\[|\\]", "");
HashMap<String, String> contact = new HashMap<>();
contact.put("name", name);
contactList.add(contact);
}
}
This is my output, I need to get the values separately like:
1
A S Peta
0
0
But not in single row:

Json String ca be parsed in JSONObject like:
try {
List<HashMap<String,String>> cityDetails= new ArrayList<HashMap<String,String>>();
JSONObject jsonObject = new JSONObject("your json string");
JSONArray jsonArray = jsonObject.getJSONArray("result");
JSONArray cityKeyArray =jsonArray.getJSONArray(0);
for(int index=1; index<jsonArray.length();index++){
HashMap<String, String> cityData = new HashMap<String, String>();
for(int dataIndex=0; dataIndex<cityKeyArray.length();dataIndex++) {
cityData.put(cityKeyArray.getString(dataIndex), jsonArray.getJSONArray(index).getString(dataIndex));
}
cityDetails.add(cityData);
}
} catch (Exception e) {
e.printStackTrace();
}
cityDetails can be used in the adapter to show value according to the keys which are in the first array of the JSON String i.e. cityKeyArray.
So, the collections will show the data as user requirements.
Hope this will help to solve your query.
Thanks and Happy coding!!!

update your code with this
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("result");
for (int i = 1; i < contacts.length(); i++) {
JSONArray contactArray = contacts.getJSONArray(i);
int id = contactArray.getInt(0);
String name = contactArray.getString(1);
String origin= contactArray.getString(2);
String destination= contactArray.getString(3);
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("name", name);
contact.put("origin", origin);
contact.put("destination", destination);
contactList.add(contact);
}
}

String name = contacts.getString(i).replaceAll("\\[|\\]", "");
Do not do this; it seems you do not have strings for your arrays.
You have nested lists, it seems, so you can access those JSON arrays via another getJSONArray(index) method
Or you could fix the source of the JSON (your server?) to return better parsable JSON

try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("result");
for (int i = 1; i < contacts.length(); i++) {
HashMap<String, String> contact = new HashMap<>();
contact.put("name", contacts.getString("name"));
contactList.add(contact);
}
}

Do this
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("result");
for (int i = 1; i < contacts.length(); i++) {
JsonArray array=contacts.get(i);
String name = array.getString("name");
HashMap<String, String> contact = new HashMap<>();
contact.put("name", name);
contactList.add(contact);
}
}

Related

Store json array keys data in separate arrayLists

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.

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

Insert JSON Array on String Array on android

I have JSON array like below format
{
"get": [],
"post": {
"_event": "get_buyers_guide_detail",
"_deviceID": "490154203237518",
"type": "cars",
"model_id": "1007"
},
"cars": [
{
"ID": 6119,
"post_title": "COROLLA",
"interior_images": [
"http://.....e8664969d20654bf2a58f1b26de70d2.jpg",
"http://........02/3bdfae250e3ce14514fe8f2f9dc3e58f.jpg",
"http://........1d14a554a2ed78d1659463ec.jpg"
],
}
]
}
I have create JSONArray for this:
JSONArray Array = entries.getJSONArray("cars");
for (int i = 0; i < Array.length(); i++) {
JSONObject detailObject = Array.getJSONObject(i);
String ID = detailObject.getString("ID");
String title = detailObject.getString("post_title");
JSONArray galleryArray = detailObject.getJSONArray("interior_images");
for(int j=0; j<galleryArray.length(); j++){
// What to do here ????
}
}
now i am confused with this format of JSON data. There is no JSONObject to get the values. How to insert these string on Array please help me find out the solution
Try this,
galleryArray.getString(j);
this should get the string at position j.
galleryArray.getString(index);
This function will return String object of corresponding index
try this
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray galleryArray = detailObject.getJSONArray("interior_images");
for(int j=0; j<galleryArray.length(); j++){
try {
JSONObject jsonObject = galleryArray.getJSONObject(j);
stringArray.add(jsonObject.toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
Try this way,hope this will help you to solve your problem.
try{
String jsonRespone="{\"get\":[],\"post\":{\"_event\":\"get_buyers_guide_detail\",\"_deviceID\":\"490154203237518\",\"type\":\"cars\",\"model_id\":\"1007\"},\"cars\":[{\"ID\":6119,\"post_title\":\"COROLLA\",\"interior_images\":[\"http://.....e8664969d20654bf2a58f1b26de70d2.jpg\",\"http://........02/3bdfae250e3ce14514fe8f2f9dc3e58f.jpg\",\"http://........1d14a554a2ed78d1659463ec.jpg\"],}]}";
JSONObject responeJson = new JSONObject(jsonRespone);
ArrayList<HashMap<String,Object>> data = new ArrayList<HashMap<String, Object>>();
JSONArray carsJsonArray = responeJson.getJSONArray("cars");
for (int i=0;i<carsJsonArray.length();i++){
HashMap<String,Object> row = new HashMap<String, Object>();
row.put("ID",carsJsonArray.getJSONObject(i).getString("ID"));
row.put("TITLE",carsJsonArray.getJSONObject(i).getString("post_title"));
JSONArray galleryArray = carsJsonArray.getJSONObject(i).getJSONArray("interior_images");
ArrayList<String> interiorImages = new ArrayList<String>();
for(int j=0; j<galleryArray.length(); j++){
interiorImages.add(galleryArray.getString(j));
}
row.put("INTERIORIMAGES",carsJsonArray.getJSONObject(i).getString("interiorImages"));
data.add(row);
}
for (HashMap<String,Object> row :data){
System.out.print("ID : "+row.get("ID"));
System.out.print("TITLE : "+row.get("TITLE"));
ArrayList<String> interiorImages = (ArrayList<String>) row.get("INTERIORIMAGES");
for (int j=0;j<interiorImages.size();j++){
System.out.print("INTERIORIMAGES +"+j+" : "+interiorImages.get(j));
}
}
}catch (Throwable e){
e.printStackTrace();
}
I think you need to use List of Map
Example:
List<Map> list = new ArrayList<Map>();
Map map = new HashMap();
map.put("userIcon", R.drawable.scott);
map.put("username", "Shen");
map.put("usertext", "This is a simple sample for SimpleAdapter");
list.add(map);
map = new HashMap();
map.put("userIcon", R.drawable.ricardo);
map.put("username", "Ricardo");
map.put("usertext", "This is a simple sample for SimpleAdapter");
list.add(map);
add this in loop

How to convert json object into string in Android

My JSON format is:
[
{
"change": 1.59,
"name": "ABC",
"price": 10.52,
"volume": 230
},
{
"change": -0.05,
"name": "DEF",
"price": 1.06,
"volume": 1040
},
{
"change": 0.01,
"name": "GHI",
"price": 37.17,
"volume": 542
}
]
I want to parse it and convert it into string. I am using this method for converting it:
JSONObject jsonObj = new JSONObject(jsonStr);
for (int i = 0; i < jsonObj.length(); i++)
{
String change = jsonObj.getString(TAG_CHANGE);
String name = jsonObj.getString(TAG_NAME);
String price = jsonObj.getString(TAG_PRICE);
String volume = jsonObj.getString(TAG_VOLUME);
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_CHANGE, change);
contact.put(TAG_NAME, name);
contact.put(TAG_PRICE, price);
contact.put(TAG_VOLUME, volume);
// adding contact to contact list
contactList.add(contact);
}
But I get an error:
/System.err(867): at org.json.JSON.typeMismatch(JSON.java:111)
How do I resolve this?
Please try it, It should work
JSONArray jsonObj = new JSONArray(jsonStr);
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
String change = c.getString(TAG_CHANGE);
String name = c.getString(TAG_NAME);
String price = c.getString(TAG_PRICE);
String volume = c.getString(TAG_VOLUME);
HashMap < String, String > contact = new HashMap < String, String > ();
contact.put(TAG_CHANGE, change);
contact.put(TAG_NAME, name);
contact.put(TAG_PRICE, price);
contact.put(TAG_VOLUME, volume);
contactList.add(contact);
}
Try this..
You are getting response as JSONArray but you are doing it as JSONObject
[ // this is JSONArray
{ // this is JSONObject
Change this
JSONObject jsonObj = new JSONObject(jsonStr);
to
JSONArray jsonObj = new JSONArray(jsonStr);
You are parsing in wrong way. your json is starts with an array containing JsonObjects. This can be identified since square braces denote JsonArray while curly braces denote JsonObject. Start with:
JSONArray jsonArr = new JSONArray(jsonStr);
then iterate through each object, get JsonObject at each index and use getString method for each key to get values.

JSON parsing is it the right way of parsing data and image in listview

I am confused How to use looping for Json response Array in another Array. The following is my jsonresponse how to loop this to get data and images in listview
`{
"status": "ok",
"posts": [
{
"id": 2498,
"title": "jigsaw lamp imported from thailand",
"content": "<p>Hi. It’s a invitation to have a look at a unique lamp shade called jigsaw lamp from thailand. Available in multi attractive colours.</p>\n",
"date": "2012-12-26 09:48:15",
"author": {
"name": "Tapas123456",
},
"attachments": [
{
"description": "",
"caption": "",
"mime_type": "image/jpeg",
"images": {
"thumbnail": {
"url": "http://site/wp-content/uploads/2012/12/646675-50x47.jpg",
}
}
]
},........
the following is the code i used to loop is this the right way of doing it?
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
posts = json.getJSONArray(KEY_POSTS);
// looping through all song nodes <song>
for(int i = 0; i < posts.length(); i++){
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(KEY_ID);
String title = c.getString(KEY_TITLE);
String date = c.getString(KEY_DATE);
String content = c.getString(KEY_CONTENT);
// Phone number is agin JSON Object
JSONObject author = c.getJSONObject(KEY_AUTHOR);
String name = author.getString(KEY_NAME);
JSONArray attachments = json.getJSONArray(KEY_ATTACHMENTS);
for(int j = 0; j < attachments.length(); j++){
JSONObject d = attachments.getJSONObject(j);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = d.getJSONObject(KEY_THUMB_URL);
String url = thumbnail.getString(KEY_URL);
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, id);
map.put(KEY_TITLE, title);
map.put(KEY_DATE, date);
map.put(KEY_NAME, name);
map.put(KEY_CONTENT, content);
// adding HashList to ArrayList
songsList.add(map);
Just Replace Following code
for(int j = 0; j < attachments.length(); j++){
JSONObject d = attachments.getJSONObject(j);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = images.getJSONObject(KEY_THUMB_URL);
String url = thumbnail.getString(KEY_URL);
}
instead of old code.

Categories

Resources