How can i parse this json file in android studio? [duplicate] - android

This question already has answers here:
Android Parse JSON Array
(3 answers)
Closed 6 years ago.
how can i parse this json file because the text do not have any particular indexing names
{
"titles": [
" Thoughts On The Works Of Providence",
"\"All Is Vanity, Saith the Preacher\"",
"\"And the sins of the fathers shall be\"",
"\"Arcturus\" is his other name",
"\"By the Waters of Babylon.\"",
"\"De Gustibus--\"",
"\"Faith\" is a fine invention",
"\"Faithful to the end\" Amended",
"\"Heaven\" -- is what I cannot reach!",
"\"Heaven\" has different Signs -- to me --",
"\"Heavenly Father\" -- take to thee",
"\"Home\"",
]
}

Like this:
JSONArray array = object.getJSONArray("titles");
for(int i = 0; i < array.length(); i ++){
String title = array.getString(i);
//Do something with the string
}
You treat the JsonArray like a string array.
However in the array you provided the JSON is invalid because of the comma on the last element of the array, you need to remove this comma to have valid JSON.

It's just a simple JSON. Do it like this.
String json = "{\"titles\":[\" Thoughts On The Works Of Providence\",\"\\\"All Is Vanity, Saith the Preacher\\\"\",\"\\\"And the sins of the fathers shall be\\\"\",\"\\\"Arcturus\\\" is his other name\",\"\\\"By the Waters of Babylon.\\\"\",\"\\\"De Gustibus--\\\"\",\"\\\"Faith\\\" is a fine invention\",\"\\\"Faithful to the end\\\" Amended\",\"\\\"Heaven\\\" -- is what I cannot reach!\",\"\\\"Heaven\\\" has different Signs -- to me --\",\"\\\"Heavenly Father\\\" -- take to thee\",\"\\\"Home\\\"\"]}";
JSONObject jsonObject = new JSONObject(json);
And for accessing your items:
JSONArray jsonArray = jsonObject.getJSONArray("titles");
for(int i=0;i<jsonArray.size(); i++){
Log.d(TAG, jsonArray.getString(i));
}

You can parse this to an instanse of this class :
public class Instance{
public String[] titles;
}
but you need to remove the last comma after home. If there is no another item after the comma, it means it is not a valid JSON string.

This should work.
JSONObject jsonObject = new JSONObject(yourString);
JSONArray jsonArray= jsonObject.getJSONArray("titles");
for (int i=0; i < jsonArray.length(); i++) {
string content = jsonArray.getString(i);
....
}

Try this:
Try{
JSONArray itemArray = jsonObject.getJSONArray("titles")
for (int i = 0; i < itemArray.length(); i++) {
String value=itemArray.getString(i);
Log.e("json", i+"="+value);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Related

Android json array: how do I get and specific string? [duplicate]

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 6 years ago.
I have a Json script which get data from a Mysql database and print it in different TextViews. The thing I want to know is how can I take for example only the "idE" value and print it in the "TextViewTitulo" TextView
try {
String response = "[{"0":"1","id":"1","1":"f3n","idE":"f3n","2":"bar","tipo":"bar"},{"0":"1","id":"1","1":"f3n","idE":"f3n","2":"bar2","tipo":"bar2"}]"
JSONArray array;
array = new JSONArray(response);
StringBuilder sb = new StringBuilder();
for (i=0; i<array.length(); i++) {
// chain each string, separated with a new line
sb.append(array.getString(i) + "\n");
}
// display the content on textview
textViewTitulo.setText(sb.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
My code works fine, but is displays the whole string of values
You have 2 objects in your JSONArray, and 1 textview to show the data in, so I'm adding append " " to separate them.
for (i=0; i<array.length(); i++) {
sb.append(array.getJSONObject(i).getString("idE"));
sb.append(" ");
//do whatever with it
}
textViewTitulo.setText(sb.toString());
Of course you can get it, you just have to iterate through the whole JSONArray. If you know the value you are looking for, you have to search for it, if you know the index - it is easier, you just have to get it. So for the first case, you could do something like:
for (int i = 0; i < array.length(); i++) {
JSONObject current = array.getJSONObject(i);
// In your case the JSONObject is more complicated
// so you need to iterate over it too
Iterator<?> keys = current.keys();
while(keys.hasNext()) {
String key = (String)keys.next();
String value = current.get(key);
// Do something with the value
}
// Or If you know what key you are looking for, you may do
String value = current.get("idE");
// Do something with value
}

Android json parsing error

My json data is given below:
[
{"Category_Id":"C1 ","Category_Name":"breakfast"},
{"Category_Id":"C2 ","Category_Name":"appetizers & snacks"},
{"Category_Id":"C3 ","Category_Name":"sandwiches & more"},
{"Category_Id":"C4 ","Category_Name":"burgers & wraps"},
{"Category_Id":"C5 ","Category_Name":"salads"},
{"Category_Id":"C6 ","Category_Name":"soup"},
{"Category_Id":"C7 ","Category_Name":"pizza & pasta"},
{"Category_Id":"C8 ","Category_Name":"kids menu"},
{"Category_Id":"C9 ","Category_Name":"main dishes"},
{"Category_Id":"C10 ","Category_Name":"oriental cuisine"},
{"Category_Id":"C11 ","Category_Name":"desserts"},
{"Category_Id":"C12 ","Category_Name":"shakes & smoothies"},
{"Category_Id":"C13 ","Category_Name":"drinks"},
{"Category_Id":"C14","Category_Name":"333"}
]
how could i parse these data and set the text in button dynamically.
String str ="[{\"Category_Id\":\"C1 \",\"Category_Name\":\"breakfast\"},{\"Category_Id\":\"C2 \",\"Category_Name\":\"appetizers & snacks\"},{\"Category_Id\":\"C3 \",\"Category_Name\":\"sandwiches & more\"},{\"Category_Id\":\"C4 \",\"Category_Name\":\"burgers & wraps\"},{\"Category_Id\":\"C5 \",\"Category_Name\":\"salads\"},{\"Category_Id\":\"C6 \",\"Category_Name\":\"soup\"},{\"Category_Id\":\"C7 \",\"Category_Name\":\"pizza & pasta\"},{\"Category_Id\":\"C8 \",\"Category_Name\":\"kids menu\"},{\"Category_Id\":\"C9 \",\"Category_Name\":\"main dishes\"},{\"Category_Id\":\"C10 \",\"Category_Name\":\"oriental cuisine\"},{\"Category_Id\":\"C11 \",\"Category_Name\":\"desserts\"},{\"Category_Id\":\"C12 \",\"Category_Name\":\"shakes & smoothies\"},{\"Category_Id\":\"C13 \",\"Category_Name\":\"drinks\"},{\"Category_Id\":\"C14\",\"Category_Name\":\"333\"}]";
JSONArray jarray;
try{
jarray = new JSONArray("");
for(int i = 0; i < jarray.length(); i++)
{
String id = jarray.getJSONObject(i).getString("Category_Id");
String name = jarray.getJSONObject(i).getString("Category_Name");
}
}catch(Exception e){}
If you get json parser error just check whether your json string is correct or not by checking it in online in any json parsing website like:-
http://jsonlint.com/
OR
http://jsonviewer.stack.hu/
For this all you need to do is a for loop to go through the Json response. Something like this should do the trick.
JSONArray jsonArray;
try{
jsonArray = new JSONArray(myJsonResponse);
for(int i = 0; i < jsonArray.length(); i++)
{
JsonObject object = new JsonObject(jsonArray.getJsonObject(i));
buttonTextString = object.getString("Category_Name);
}
} catch(Exception e) {}
You can parse JSONArray before then parse JSONObject to parse each element on your json data. And final setText for button each element you can parse

How to fetch Data From JSON

I have following data from JSON
{
"MenuName": "starter dish",
"SubMenu": [
"pizza dish1",
"pizza dish2"
],
"Price": [
"100",
"110"
]
},
From here i can easily fetch data from "Menuname" key as starter dish but when I fetch data from "Submenu" I get whole string as ["pizza dish1", "pizza dish2"].
Please suggest me way to differentiate both pizza dish1 and pizza dish2
Submenu and Price is not String it is JSONArray so you will need to use for-loop to get all values from Submenu JSONArray as:
JSONArray jsonsubmenu=yourjsonobject.getJSONArray("Submenu");
for(int i=0;i < jsonsubmenu.length();i++){
// get all values from jsonsubmenu JSONArray..
String str_value=jsonsubmenu.optString(i);
....
}
try this
for (int i = 0; i < jsonArray.length(); i++) {
jsonArray.getJSONObject(i).getInt("SubMenu");
}
you can use this link for creating POGO class for your response. It will automatically generate class for your response.
Use google GSON library to parse your response.
or you can simply create a JSON Array or Objects to parse it. in your case it is JSON Object or JSON arrays.
Hi There in that senarerio you have to use
JSONArray _submenu = object.getJSONArray("SubMenu");
for (int i = 0; i < _submenu.length(); i++) {
String text = _submenu.getString(i);
}
JSONArray _price = object.getJSONArray("Price");
for (int i = 0; i < _price.length(); i++) {
String text = _price.getString(i);
}
You can retrieve array values and store it in string[] and use them as per your need. i.e., as follows..
try {
JSONObject jObject = new JSONObject(jsonString);
JSONArray jSubmenu = jObject.getJSONArray("SubMenu");
subMenu = new String[jSubmenu.length()];
for (int i = 0; i < subMenu.length; i++) {
subMenu[i] = jSubmenu.getString(i);
}
JSONArray jPrice = jObject.getJSONArray("Price");
price = new String[jPrice.length()];
for (int i = 0; i < price.length; i++) {
price[i] = jPrice.getString(i);
}
} catch (Exception e) {
// TODO: handle exception
}
Just to throw in a quickie - read up on, and use GSON.
For simple small jobs I find it is the best. Not the fastest running for complex, or long structures, but really quick on the dev side.
Here's the link: google-gson

complex Json Parsing in Android

In my app, i want to parse json response which is in the format
{"quote":[{"orderId":"3209926"},{"totalpages":1}]}
below is the code which i had done,But the problem is how to get the "totalpages" value?
try {
JSONObject jObject = new JSONObject(result);
JSONArray jArray = jObject.getJSONArray("quote");
for (int i = 0; i < jArray.length(); i++)
{
JSONObject offerObject = jArray.getJSONObject(i);
current.orderId = offerObject.getInt("orderId");
It shows error when i use
current.totalpage= offerObject.getInt("totalpages");
Anybody knows how to parse this?THanks in advance
Note that getInt(), like other get-functions of JSONObject throw JSONException if the object does not contain the key requested. Thus, before you request the key you should use hasKey() to determine whether the object contains the key.
For example, inside the for loop you can do the following:
JSONObject offerObject = jArray.getJSONObject(i);
if(offerObject.has("orderId") {
current.orderId = offerObject.getInt("orderId");
}
if(offerObject.has("totalpages") {
current.totalpage= offerObject.getInt("totalpages");
}
You can also add a flag and a check after the loop to ensure that both orderId and totalpages were present in the JSON data.
I dont know why your json is having that structure. But if you want to parse it then you will have to do something like the following with the has function.
for (int i = 0; i < jArray.length(); i++) {
JSONObject offerObject = jArray.getJSONObject(i);
if(offerObject.has("orderId")) {
current.orderId = offerObject.getInt("orderId");
} else if(offerObject.has("totalpages")) {
current.totalpage= offerObject.getInt("totalpages");
}
}

Android: Decoding JSON

[{"placeID":"p0001","placeName":"INTI International University","placeType":"Education","placeLat":"2.813997","placeLng":"101.758229","placePict":""},{"placeID":"p0002","placeName":"Nilai International College","placeType":"Education","placeLat":"2.814179","placeLng":"101.7700107","placePict":""}]
How do I decode the JSON sent from my PHP script on Android?
please try this
String s = "[{\"placeID\":\"p0001\",\"placeName\":\"INTI International University\",\"placeType\":\"Education\","
+ "\"placeLat\":\"2.813997\",\"placeLng\":\"101.758229\",\"placePict\":\"\"},"
+ "{\"placeID\":\"p0002\",\"placeName\":\"Nilai International College\",\"placeType\":\"Education\",\"placeLat\":\"2.814179\",\"placeLng\":\"101.7700107\",\"placePict\":\"\"}]";
ArrayList<String> arrplaceID = new ArrayList<String>();
ArrayList<String> arrplaceName = new ArrayList<String>();
try {
JSONArray arr = new JSONArray(s);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonObject = arr.getJSONObject(i);
arrplaceID.add(jsonObject.optString("placeID"));
arrplaceName.add(jsonObject.optString("placeName"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < arrplaceID.size(); i++) {
Log.e("arr[" + i + "] place Name", arrplaceName.get(i));
}
What is the problem in this Please Read this tutorial for parsing JSON it might be helpful in future also.json parsing link
Follow below points.
1) it seems the response you are getting is Json Array. so create one json array by response string.
JSonArray jArray = new JsonArray(responseString);
2) now you have your response in jArray. now iterate a loop and take json object from JsonArray, in your case you have two json objects.
for(i,i<jArray.size,i++)
{
JsonObject obj=jArray.get(i);
// here you got your first entry in jsonObject.
// nor use this obj according to ur need. you can say obj.getString("placeID");
// and so on.
}
refer this to understand more on json link
use JSONArray class:
JSONArray jsonplaces = new JSONObject(stringPlaces);
then your able to iterate throught array by using for-loop:
for (int i = 0; i < jsonplaces.length(); i++) {
JSONObject jsonplace = (JSONObject) jsonplaces.get(i);
//read items, for example:
String placeName = jsonplace.getString("placeName");
}

Categories

Resources