I am trying to parse JSON response where i am able to parse title,date, content and name but iam not able to parse url and display it in Listview. when i parse the url it is displaying image url in textview Can anybody direct me in right path
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 siteurl = c.getString(KEY_SITEURL);
String title = c.getString(KEY_TITLE);
String date = c.getString(KEY_DATE);
String content = c.getString(KEY_CONTENT);
// to remove all <P> </p> and <br /> and replace with ""
content = content.replace("<br />", "");
content = content.replace("<p>", "");
content = content.replace("</p>", "");
//authornumber is agin JSON Object
JSONObject author = c.getJSONObject(KEY_AUTHOR);
String name = author.getString(KEY_NAME);
String url1 = null;
String slug1 = null;
try {
JSONArray atta = c.getJSONArray("attachments");
for(int j = 0; j < atta.length(); j++){
JSONObject d = atta.getJSONObject(j);
slug1 = d.getString(KEY_SLUG);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = images.getJSONObject(KEY_THUMB_URL);
url1 = thumbnail.getString(KEY_URL);
}
} catch (Exception e) {
e.printStackTrace();
}
// 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_SITEURL, siteurl);
map.put(KEY_DATE, date);
map.put(KEY_NAME, name);
map.put(KEY_CONTENT, content);
map.put(KEY_SLUG, slug1);
map.put(KEY_URL, url1);
// adding HashList to ArrayList
songsList.add(map);
}
}catch (JSONException e) {
e.printStackTrace();
}
Related
String jsonString = "{"name":"kd","isMe":"yes","time":"10:12 AM"},{"name":"you","isMe":"no","time":"10:12 AM"}";
JSONObject jValueObject = new JSONObject(jsonString);
Iterator<?> values = jValueObject.keys();
while(values.hasNext()){
String final_key = (String)values.next();
String final_value = jValueObject.getString(final_key);
if (final_value != "")
map.put(final_key, final_value);
if (!final_key.equals("")) {
sbkeys.append(final_key).append(',');
}
}
Log.e("Final_Map", String.valueOf(map));
itemList = sbkeys.toString();
Output : {name=kd,isMe=yes,time=10:12 AM}
Try this code:
HashMap map = new HashMap<String, String>();
Iterator<?> values = jValueObject.keys();
while(values.hasNext()) {
String final_key = (String)values.next();
String final_value = jValueObject.optString(final_key, "");
if (!final_value.equals(""))
map.put(final_key, final_value);
}
for (k : map.keySet()) {
Log.d("Final_Map", "map[" + key + "] : " + map.get(k));
}
this is a duplicate question,
please check these answers
Convert JSONObject to Map
use Jackson(http://jackson.codehaus.org/) from http://json.org/
HashMap<String,Object> result =
new ObjectMapper().readValue(<JSON_OBJECT>, HashMap.class);
or
You can use Gson() (com.google.gson) library if you find any difficulty using Jackson.
HashMap<String, Object> yourHashMap = new Gson().fromJson(yourJsonObject.toString(), HashMap.class);
First off, if its a json array that you need in the string then wrap your string in square brackets. (I'd expect you've escaped the double quotes as well).
String jsonString = "[{\"name\":\"kd\",\"isMe\":\"yes\",\"time\":\"10:12 AM\"},{\"name\":\"you\",\"isMe\":\"no\",\"time\":\"10:12 AM\"}]";
Now its a JSONArray and not a JSONObject. So to get a list of Maps,
JSONArray jValueArray = new JSONArray(jsonString);
List<Object> listOfMaps = jValueArray.toList();
System.out.println(listOfMaps);
Prints:
[{isMe=yes, name=kd, time=10:12 AM}, {isMe=no, name=you, time=10:12 AM}]
JSONObject jObject = new JSONObject(jsonString);
Iterator<?> keys = jObject.keys();
while (keys.hasNext()) {
map = new HashMap<String, String>();
sbkeys = new StringBuilder();
String key = (String) keys.next();
String value = jObject.getString(key);
try{
JSONObject jValueObject = new JSONObject(value);
Iterator<?> values = jValueObject.keys();
while (values.hasNext()) {
String final_key = (String) values.next();
String final_value = jValueObject.getString(final_key);
if (!final_value.equalsIgnoreCase("")) {
map.put(final_key, final_value);
sbkeys.append(final_key).append(',');
}
}
}catch (Exception e){
e.fillInStackTrace();
}
try {
//// Your Code..
} catch (Exception e) {
errorCode = "1";
}
}
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);
}
}
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
Sometime json array appears with image url's and sometimes it is empty. I am using the following code where array with image url displaying data and image in listview but when array is empty then data is also not displaying. How can i slove this? Any answer will be appreciated
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 {
JSONArray 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);
//authornumber is agin JSON Object
JSONObject author = c.getJSONObject(KEY_AUTHOR);
String name = author.getString(KEY_NAME);
JSONArray atta = c.getJSONArray("attachments");
for(int j = 0; j < atta.length(); j++){
JSONObject d = atta.getJSONObject(j);
String slug = d.getString(KEY_SLUG);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = images.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);
map.put(KEY_SLUG, slug);
map.put(KEY_URL, url);
// adding HashList to ArrayList
songsList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing json data ArrayList
adapter=new LazyAdapter(this, songsList);
list.setAdapter(adapter);
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.