How to convert json object into string in Android - 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.

Related

Unable to get JSON values separately in 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);
}
}

List json expendable child not accurate

This is my JSON file,
[{
"Title": "AY",
"Items": [{
"Name": "Alex",
"RoadNameShort": "AY"
}, {
"Name": "Kep",
"RoadNameShort": "AY"
}, {
"Name": "Lower",
"RoadNameShort": "AY"
}]
}, {
"Title": "BK",
"Items": [{
"Name": "Chantek",
"RoadNameShort": "BK"
}, {
"Name": "Wood",
"RoadNameShort": "BK"
}]
}]
This is my Java Code,
listDataHeader = new ArrayList<String>();
listDataHeade = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
HashMap<String, String> contact = new HashMap<>();
// Adding child data for lease offer
List<String> lease_offer = new ArrayList<String>();
JSONArray array = new JSONArray(jsonstr);
for (int i = 0; i < array.length(); i++) {
// tmp hash map for single contact
JSONObject c = array.getJSONObject(i);
listDataHeader.add(c.getString("Title"));
String title = c.getString("Title");
JSONArray items = c.getJSONArray("Items");
for (j = 0; j < items.length(); j++) {
JSONObject item = items.getJSONObject(j);
String name = item.getString("Name");
Log.d("email", name);
listDataHeade.add(item.getString("Name"));
lease_offer.add(item.getString("Name"));
// Header into Child data
listDataChild.put(listDataHeader.get(i), lease_offer);
}
}
For parent I used Title. Child is Name. I got correctly for group which is title AY, BK. But my problem is for child. Names Chantek and wood should be under group BK, not in group AY. But in group AY, I also get Chantek and wood be as child.
Try to move listDataChild outside inner loop because you need to add all child to parent list after iterate all childs and initialise lease_offer before inside loop start because each parent need to create new child list as below :
JSONArray array = new JSONArray(jsonstr);
for (int i = 0; i < array.length(); i++) {
// tmp hash map for single contact
JSONObject c = array.getJSONObject(i);
String title = c.getString("Title");
listDataHeader.add(title);
JSONArray items = c.getJSONArray("Items");
/ Adding child data for lease offer
List<String> lease_offer = new ArrayList<String>();
for (j = 0; j < items.length(); j++) {
JSONObject item = items.getJSONObject(j);
String name = item.getString("Name");
Log.d("email", name);
listDataHeade.add(name);
lease_offer.add(name);
}
// Header into Child data
listDataChild.put(listDataHeader.get(i), lease_offer);
}

Get JSONObject - Android

Here is my JSON:
{
"id": "11111",
"title": "title?",
"url": "www.example.com",
"fulltext": {
"page1": "<p>balblabba</p>",
"page2": "<p>avavaava</p>"
},
"related_articles": [
{
"id": "123",
"title": "title",
"image_name": "www.example.com/image1.png"
}
]
}
I need to put everything in Strings. I'm using this code:
String data = JSON TEXT!!!;
JSONObject jRealObject = new JSONObject(data);
String title = jRealObject.getString("title").toString();
String url = jRealObject.getString("url").toString();
String fulltext = jRealObject.getString("fulltext").toString();
String page1 = ????
String page2 = ????
jArray = jRealObject.getJSONArray("related_articles");
for (int i = 0; i < jArray.length(); i++) {
jRealObject = jArray.getJSONObject(i);
String relatedId = jRealObject.getString("id").toString();
String relatedTitle = jRealObject.getString("title").toString();
String relatedImage = jRealObject.getString("image_name").toString();
}
I'm getting everything, But I want to split "fultext" into two variables. but I don't know how can I get "page1" and "page2".
Here in your response "fulltext" is another Jsonobject use below code to get other data.
JSONObject fulltextobj = jRealObject.getJSONObject("fulltext");
String page1 = fulltextobj.getString("page1");
String page2 = fulltextobj.getString("page2");
JSONObject obj = jRealObject.getJSONObject("fulltext");
String var1 = obj.getString("page1");
String var2 = obj.getString("page2");
EDIT: You have a JSONObject nested into another JSONObject. fulltext is not a String, is a JSONObject indeed, so you have to get a JSONObject from parent
Try this way,hope this will help you to solve your problem.
try{
JSONObject jsonObject = new JSONObject("{\"id\":\"11111\",\"title\":\"title?\",\"url\":\"www.example.com\",\"fulltext\":{\"page1\":\"<p>balblabba</p>\",\"page2\":\"<p>avavaava</p>\"},\"related_articles\":[{\"id\":\"123\",\"title\":\"title\",\"image_name\":\"www.example.com/image1.png\"}]}");
HashMap<String,Object> responseMap = new HashMap<String, Object>();
ArrayList<HashMap<String,String>> articleList = new ArrayList<HashMap<String, String>>();
responseMap.put("id",jsonObject.getString("id"));
responseMap.put("title",jsonObject.getString("title"));
responseMap.put("url",jsonObject.getString("url"));
JSONObject fullTextJsonObject = jsonObject.getJSONObject("fulltext");
responseMap.put("page1",fullTextJsonObject.getString("page1"));
responseMap.put("page2",fullTextJsonObject.getString("page2"));
JSONArray relatedArticleJsonArray = jsonObject.getJSONArray("related_articles");
for(int i=0;i<relatedArticleJsonArray.length();i++){
HashMap<String,String> articleRow = new HashMap<String, String>();
articleRow.put("id", relatedArticleJsonArray.getJSONObject(i).getString("id"));
articleRow.put("title", relatedArticleJsonArray.getJSONObject(i).getString("title"));
articleRow.put("image_name", relatedArticleJsonArray.getJSONObject(i).getString("image_name"));
articleList.add(articleRow);
}
responseMap.put("related_articles",articleList);
System.out.print("id : "+responseMap.get("id").toString());
System.out.print("title : "+responseMap.get("title").toString());
System.out.print("url : "+responseMap.get("url").toString());
System.out.print("page1 : "+responseMap.get("page1").toString());
System.out.print("page2 : "+responseMap.get("page2").toString());
ArrayList<HashMap<String,String>> list = (ArrayList<HashMap<String,String>>)responseMap.get("related_articles");
for (HashMap<String,String> row : list){
System.out.print("id : "+row.get("id"));
System.out.print("title : "+row.get("title"));
System.out.print("image_name : "+row.get("image_name"));
}
}catch (Throwable e){
e.printStackTrace();
}
You are making string again toString which having no sense. please do some modification in your code .I have also done changes that you requrie.
String data = JSON TEXT!!!;
JSONObject jRealObject = new JSONObject(data);
String title = jRealObject.getString("title");
String url = jRealObject.getString("url");
String fulltext = jRealObject.getString("fulltext");
JSONObject obj = jRealObject.getJSONObject("fulltext");
String strPage1 = obj.getString("page1");
String strPage2 = obj.getString("page2");
jArray = jRealObject.getJSONArray("related_articles");
for (int i = 0; i < jArray.length(); i++) {
jRealObject = jArray.getJSONObject(i);
String relatedId = jRealObject.getString("id");
String relatedTitle = jRealObject.getString("title");
String relatedImage = jRealObject.getString("image_name");
}

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.

parsing a JSON array from a string

can some one please get me the json parsing for an json array
line = "contexts": [
{
"uuid": "6686feaa-a254-42ec-a662-c36f70f7a586",
"name": "School",
},
{
"uuid": "bd8e6c44-d461-4bbe-8946-a3717dc7fa7f",
"name": "Teaching",
}]
I need uuid and name into to string arrays. I tried
String[] x = new String[10];
String[] y = new String[10];
JSONArray jArray = new JSONArray(line);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
x = json_data.getString("name");
y = json_data.getString("uuid");
}
I get type mismatch error when I run this. The type of line is string which I return from server.
use i to add elements to Array's:
String[] x = new String[10];
String[] y = new String[10];
JSONObject json=new JSONObject(line);
JSONArray jArray =json.getJSONArray("contexts");
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
x[i] = json_data.getString("name");
y[i] = json_data.getString("uuid");
}
you can use http://jsonviewer.stack.hu/ for checking json is valid or not. and use ArrayList instead of Array for getting items dynamically from web service
Its neither JSONObject, nor JSONArray, return string from server like below:
line = {"contexts": [
{
"uuid": "6686feaa-a254-42ec-a662-c36f70f7a586",
"name": "School",
},
{
"uuid": "bd8e6c44-d461-4bbe-8946-a3717dc7fa7f",
"name": "Teaching",
}]}
and then parse like below code:
JSONObject json=new JSONObject(line);
JSONArray jArray =json.getJSONArray("contexts");

Categories

Resources