Android: Decoding JSON - android

[{"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");
}

Related

Combining nested json for loop

I have two forloop in which the data is added to different ArrayList. Now my question is how do we combine these two arraylist?
Below is the code which i tried, but not working. Please give me solution for the same. TIA
try {
JSONObject object = new JSONObject(response);
status = object.getString("status");
if (status.equals("200")) {
rest.dismissProgressdialog();
JSONArray jsonArray = object.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
New_Service_Model_1 new_service_model = new New_Service_Model_1();
new_service_model.setMain_name(jsonObject.getString("main_name"));
new_service_model.setSmid(jsonObject.optInt("smid"));
JSONArray jsonArray1 = jsonObject.getJSONArray("sub_service");
//sub_services_list.clear();
sub_services_list = new ArrayList<>();
for (int j = 0; j < jsonArray1.length(); j++) {
JSONObject jsonObject1 = jsonArray1.getJSONObject(j);
New_Sub_Service_Model_1 sub_service_model = new New_Sub_Service_Model_1();
sub_service_model.setSmid(jsonObject1.optString("smid"));
sub_service_model.setSbid(jsonObject1.optInt("sbid"));
sub_service_model.setSub_name(jsonObject1.optString("sub_name"));
sub_service_model.setDesc(jsonObject1.optInt("desc"));
sub_service_model.setSt_cust(jsonObject1.optInt("st_cust"));
sub_service_model.setSt_pro(jsonObject1.optInt("st_pro"));
sub_service_model.setExist_cust(jsonObject1.optInt("exist_cust"));
sub_service_model.setExist_prov(jsonObject1.optInt("exist_prov"));
sub_services_list.add(sub_service_model);
}
new_service_model.setSub_service_list(sub_services_list);
services_list.add(new_service_model);
service_list_adapter = new Service_List_Adapter_1(this, services_list, service_costMain_interface);
rclyrview_services.setAdapter(service_list_adapter);
service_list_adapter.notifyDataSetChanged();
}
} else {
rest.dismissProgressdialog();
Toast.makeText(Service_Manage.this, "No Data found", Toast.LENGTH_SHORT).show();
}
Instead of parsing the json response manually.
Paste you json here http://www.jsonschema2pojo.org/ and use GSON or Jackson whichever is convenient for parsing the response.
There are many tutorials available which can give you a quick overview of how things can be done. Worth a try if your app has many places where you want to have Json parsing.

How to parse json data and load it in the Listview

I am getting a json object from the api, I want to parse this json object and get the text value. I am using volley library and need to load it in listiew adapter.The json is object-array-object type.This is my Json object. Can you please help.
{"result":[{"id":"1","ExpendName":"rice","Cost":"500","Dates":"2018-01-09 11:13:58"},{"id":"2","ExpendName":"Meat","Cost":"550","Dates":"2018-01-09 11:17:27"},{"id":"3","ExpendName":"Fish","Cost":"250","Dates":"2018-01-09 11:21:30"},{"id":"4","ExpendName":"Pant","Cost":"700","Dates":"2018-01-09 11:36:45"},{"id":"5","ExpendName":"Shirt","Cost":"1000","Dates":"2018-01-09 11:50:11"},{"id":"6","ExpendName":"Tea","Cost":"55","Dates":"2018-01-09 13:37:42"},{"id":"7","ExpendName":"Lunch, Tea, Transport ","Cost":"750","Dates":"2018-01-09 13:41:29"},{"id":"8","ExpendName":"Breakfast ","Cost":"30","Dates":"2018-01-10 05:34:07"},{"id":"9","ExpendName":"Train","Cost":"460","Dates":"2018-01-11 05:32:42"},{"id":"10","ExpendName":"Bus","Cost":"1250","Dates":"2018-01-11 05:33:11"},{"id":"11","ExpendName":"Train","Cost":"500","Dates":"2018-01-11 10:03:00"}]}
You would normally parse the data this way:
try {
JSONObject jsonObject = new JSONObject(rawData);
JSONArray jsonArray = jsonObject.getJSONArray("result");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject mealObject = jsonArray.getJSONObject(i);
String id = mealObject.getString("id");
String expendName = mealObject.getString("ExpendName");
String cost = mealObject.getString("Cost");
String date = mealObject.getString("Dates");
//Do whatever you want with the data
}
} catch (JSONException e) {
e.printStackTrace();
}

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

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

Json data extracting in android

i want to extract the given json arry in android,
[{"Outofserviceday":{"outofservice":"2013-02-22"}},
{"Outofserviceday":{"outofservice":"2013-02-27"}},
{"Outofserviceday":{"outofservice":"2013-02-28"}}]
i have the code for extracting the json data like given below
[{"Requestcard":{"id":"994","userprofile_id":"14","userprofile_name":"Syed
Imran","company_name":"DLF Akruti Park, Hinjewadi, Pune,
Maharashtra","sex":"male","travel_date":"2013-02-12"}}]
in this case we can retrive the json boject using the code
JSONObject menuObject = json_data.getJSONObject("Requestcard");
and retrieve each element by
requestid= menuObject.getString("id");
But in the first case how we identify each Outofserviceday in the json array ? and How extract each data ???
you can do something like below, can create jsonArray from string json data and then can extracts json objects in a loop or so.
String json =" [{\"Outofserviceday\":{\"outofservice\":\"2013-02-22\"}}]"; //json-data which is basically a json array
JSONArray jArray = new JSONArray(json); / creating an jsonarray
for (int i = 0; i < jArray.length(); i++) {
// you can have jsonObject from json array here in the loop
}
Try this:
JSONObject json = new JSONObject(result);
JSONArray json1= json.getJSONArray("data");
if (json1.length()!=0) {
for (int i = 0; i < json1.length(); i++) {
String name = json1.getJSONObject(i).getString("name");
}
}
With the help of below code you can retrieve the value of outofservice
JSONArray jArray = new JSONArray(your data);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jOutOfServiceDay = jArray.getJSONObject(i);
JSONObject jobj = jOutOfServiceDay.getJSONObject("Outofserviceday");
Log.i("Required data is:", "" + jobj.getString("outofservice"));
}

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

Categories

Resources