How to print php response JSON response - android

How to print php response json response in android?
I am android developer but I don't have any idea about json parsing.
{
"details": [
{
"p_id": "19",
"cat_id": "1",
"p_name": "Papad",
"p_namecode": "[01]Papad",
"p_image":
"p_price": "20",
"p_quantity": "2",
"p_code": "25",
"p_discount": "10",
"p_packing": "2",
"p_type": "small",
"p_status": "1",
"p": [
{
"q_id": "16",
"p_id": "19",
"q_weight": "25-gm",
"q_price": "150",
"q_beg": "50 bunch",
"q_status": "1"
},
{
"q_id": "17",
"p_id": "19",
"q_weight": "50-gm",
"q_price": "200",
"q_beg": "50-bunch",
"q_status": "1"
}
]
},
{
"p_id": "23",
"cat_id": "1",
"p_name": "Palak Papad",
"p_namecode": "[03]Palak",
"p_image":
"p_price": "200",
"p_quantity": "5",
"p_code": "02",
"p_discount": "15",
"p_packing": "4",
"p_type": "small",
"p_status": "1",
"p": [
{
"q_id": "19",
"p_id": "23",
"q_weight": "50- gm",
"q_price": "15",
"q_beg": "50 bunch",
"q_status": "1"
},
{
"q_id": "20",
"p_id": "23",
"q_weight": "1-kg",
"q_price": "30",
"q_beg": "50 bunch",
"q_status": "1"
}
]
}
],
"success": true,
"message": "Category and Sub Category"
}

Try this for json data parsing
String jsonResult = {JSON-RESULT-IN-STRING};
JSONObject data = new JSONObject(jsonResult);
boolean success = data.getBoolean("success");
String message = data.getString("message");
JSONArray detailArray = new JSONArray(data.getString("details"))
for (int i=0; i<detailArray.length(); i++) {
JSONObject detail = detailArray.getJSONObject(i);
String pID = detail.getString("p_id");
String catID = detail.getString("cat_id");
....
....
....
}

First of all, you need to understand your JSON structure. You need GSON gradle for easy to convert your PHP response to java class object.
add this line in app level gradle.
compile 'com.google.code.gson:gson:2.8.2'
To understand your JSON data see image below. It is an exact representation of your data.
Your JSON data contains an array of Details, a boolean value success and String called message. But your Detail array contains another array called p. for better understanding see image below.
Now we are ready to go.
Create Java class P as I created below.
public class P {
public int q_id;
public int p_id;
public String q_weight;
public int q_price;
public String q_beg;
public int q_status;
}
Create new java class Detail. see carefully and create a complete class. you can take reference from the first image.
public class Detail {
public int p_id;
public int cat_id;
public String p_name;
public String p_namecode;
.
.
.
public int p_status;
public ArrayList<P> p;
}
Now we need a final class you can name it anything.
public class Product {
public ArrayList<Detail> details;
public boolean success;
public String message;
}
Now, whenever you receive your PHP response string you can convert it into java object like this.
Product d = new Product();
String response = "your_php_response_goes here";
Gson gson = new Gson();
d = gson.fromJson(response, Product.class);
Your whole response data is inside d object. To retrieve data you can do like this.
String p_name = d.details.get(0).p_name;
int p_quantity = d.deatails.get(0).p_quantity;

Related

Can't access some member of JSON array Android

I have JSON array like this
[
{
"ride_id": "48",
"user_id": "22",
"event_id": "42",
"driver_id": "0",
"pick_up_location": "11111"
},
{
"ride_id": "48",
"user_id": "21",
"event_id": "42",
"driver_id": "0",
"pick_up_location": "11111"
},
{
"name": "ofir rosner",
"image": "",
"address": "Yokne\\'am Illit, Israel"
},
{
"name": "hhhh",
"image": "profilePictureOfUserId22.JPG",
"address": "ffffd"
}
]
im using OKhttp3 to retrieve my data like
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
JSONObject object = array.getJSONObject(i);
...........
but the object of JSONObeject in place i only contains
{"ride_id":"50","user_id":"2","event_id":"44","driver_id":"0","pick_up_location":"11111"}
but I want to be able to do something like this object.setString("name")
or to get to the object in the place i for name, image and address
Your all object don't have name key-value pair so you can use optString , It returns an empty string if there is no such key
JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
JSONObject object = array.getJSONObject(i);
String name = object.optString("name");
// optionally use object.optString("name","No Name Found");
// To display some default string as name
if(!name.isEmpty()){
// we got the data , use it
Log.i("name is ",name); // display data in logs
}
}
or you can use has which Determine if the JSONObject contains a specific key.
JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
JSONObject object = array.getJSONObject(i);
String name;
if(object.has("name")){
name = object.optString("name"); // got the data , use it
}
}
{ // this object has no "name" key-value pair and so does some other object
"ride_id": "48",
"user_id": "22",
"event_id": "42",
"driver_id": "0",
"pick_up_location": "11111"
}

Empty json array is being returned while retrieving values from gson

Following is my POJO class
public class Favourite {
public static List<LocalTrack> favourite;
public Favourite() {
favourite = new ArrayList<>();
}
public List<LocalTrack> getFavourite() {
return favourite;
}
}
Im saving the json as follows in my shared preference
public static class SaveFavourites extends AsyncTask {
#Override
protected Void doInBackground(Void... params) {
String json5 = gson.toJson(favourite);
prefsEditor.putString("favouriteTracks", json5);
prefsEditor.commit();
return null;
}
}
Following are the fields which refers to POJO class
public static Favourite favouriteTracks =new Favourite();
public static List favourite = favouriteTracks.getFavourite();
Im using the following class to access the json stored as follows,
String json5 = mPrefs.getString("favouriteTracks", "");
Arrays.toString(gson.fromJson(json5, Favourite[].class))
But it always returns empty array though it was not empty while saving. When im saving, it has got a json array with multiple json objects but while retrieving, it is an empty json array.
How can I be able to sort this out?
Following is my json response
[
{
"album": "http://MyMp3Song.Com",
"artist": "04 - Thai Mannai Vanakka",
"index": "#",
"path": "/storage/sdcard1/Download/04 - Thai Mannai Vanakkam(MyMp3Song.Com).mp3",
"title": "04 - Thai Mannai Vanakkam(MyMp3Song.Com)",
"duration": 369424,
"id": 32004
},
{
"album": "http://MyMp3Song.Com",
"artist": "04 - Thai Mannai Vanakka",
"index": "#",
"path": "/storage/sdcard1/Download/04 - Thai Mannai Vanakkam(MyMp3Song.Com).mp3",
"title": "04 - Thai Mannai Vanakkam(MyMp3Song.Com)",
"duration": 369424,
"id": 32004
}
]

How to retrieve a multidimensional array using json object?

I created an app that stream video from server, on server side (PHP) I use this code to pass the MySQL query result via JSON array contain a result of video title size and views.
$query="select * from video_tble ;";
$result=mysqli_query($con,$query);
$row=mysqli_fetch_all($result,MYSQLI_ASSOC);
$respones_result=array();
$response_result=$row;
echo json_encode(array("server_response_result"=>$response_result));
But I don't know how to retrieve a multidimensional array using JSON object.
JSONObject jsonObject1=new JSONObject(json);
JSONArray jsonArray1=jsonObject1.getJSONArray("server_response_result");
JSONObject JO1=jsonArray1.getJSONObject(0);
String [] title =...?
If it was a name value pair then I follow this strategy:
String title1=JO1.getString("title");
But I don't know what to do on multidimensional array.
Hi you need a for loop like this
for(int i;i<jsonArray1.size();i++){
JSONObject JO1=jsonArray1.getJSONObject(i);
String title1=JO1.getString("title");
}
To parse this json
{
"server_response_result": [{
"videoid": "1",
"videotitle": "Metr‌​o Shoes",
"userid": "7",
"category": "Fashion",
"dou": "0000-00-00",
"rate": "3",
"vstatus": "A",
"vcount": "321",
"location": "adstreamer\\uploads\\ramesh#gmail.com\\1.mp4"
}, {
"videoid": "2",
"videotitle": "Lijn the bus",
"userid": "7",
"category": "App",
"dou": "0000-00-00",
"rate": "4",
"vstatus": "A",
"vcount": "145",
"location": "adstreamer\\uploads\\ramesh#gmail.com\\2.mp4"
}]
}
You have to do following steps (saying you have the server response in jsonObject.
ArrayList<SomeModel> modelList = new ArrayList<>();
JSONArray serverResponseResult = jsonObject.getJsonArray("server_response_result");
for (int i = 0; i < serverResponseResult.length(); i++) {
JSONObject result = serverResponseResult.get(i);
String videoId = result.getString("videoid");
String videoTitle = result.getString("videotitle");
...
// instead of using String, set the values in the model class
modelList.add(/* model */);
}

Read Android Local Database Data ,make it as JSON Format ,Send to webServer Using RestAPI

1.I am taking data from Local Database every 10 mins sending to web server.
2.after reading from Local database , make Full database data as Json format then send to Webserver from android.
I want to make Like this:
[
{
"$id": "2",
"Contact": "999",
"Lat": "465465",
"Long": "65465",
"Time": "654654",
"Msg": "1"
},
{
"$id": "3",
"Contact": "12131321",
"Lat": "3413132",
"Long": "54564",
"Time": "54654",
"Msg": "1"
}
]
Reading from Local Database:
List<LocationPOJO> val = dbconnectorForlocation.getAllvalues();
Log.i("MY data String ",val.toString());
for(int i=0;i<val.size();i++)
{
ImeiStringval = val.get(i).getIMEIString();
LatstringVal = val.get(i).getLatString();
LongStringVal = val.get(i).getLongString();
StatusStingVal = val.get(i).getStatusString();
TimeandDateVal=val.get(i).getTImeandDate();
}
Please,help me how to do this.
Try this
JSONObject json;
JSONArray jsonArray = new JSONArray();
for(int i=0;i<dbData.size;i++)
{
json= new JSONObject();
json.put("$id", dbData.get(i).getId());
json.put("Contact", dbData.get(i).getContact());
json.put("Lat", dbData.get(i).getLat());
json.put("Long", dbData.get(i).getLong());
json.put("Time", dbData.get(i).getTime());
json.put("Msg", dbData.get(i).getMsg());
jsonArray.put(json);
}

Android Json parsing with sqlite

I am new in android JSON parsing android.
Below I mentioned my JSON value, please give the solution to how to parse the JSON value, thanks in advance my JSON Data:
Here I have category, categorybook, subcategory inside have subbook. I want to parse all the value and store it into sqlite with separate.
Like category book and sucategory book are stored seperate column in android sqlite table:
[
"category": {
"id": "1",
"name": "Education",
"categorybooks": [],
"subcategory": [
{
"id": "1",
"name": "tamil",
"subcategorybooks": []
},
{
"id": "2",
"name": "english",
"subcategorybooks": []
},
{
"id": "5",
"name": "maths",
"subcategorybooks": []
},
{
"id": "6",
"name": "science,
"subcategorybooks": []
},
{
"id": "7",
"name": "social",
"subcategorybooks": []
}
}
]
Here i have category 2 and its sub category books:
[
"category": {
"id": "2",
"name": "sports",
"categorybooks": [
{
"id": "4",
"name": "football",
},
{
"id": "5",
"name": "cricket",
}
],
"subcategory": []
}
]
First of all, you will need the VolleyLibrary. Then, you will need the GSON library. When creating GSON Request, you put the Object you want to get deserialized automatically from JSON, so you wont have to parse it manualy.
Second thing, you would want to create a db class that extends SQLiteHelper. When you create database, add the methods for adding, update and removing a row for every table that you create.
Below are the links that you need.
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
https://medium.com/android-news/android-networking-i-okhttp-volley-and-gson-72004efff196#.wp5lstsfv
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
I will assume you already have the content of your json, if not you can use any Http Connection to get the content.
You can use Gson to parse your json content, first of all, you need to create your models based on your Json:
//note: Gson identify the attributes name as the same of from your
//json, if not you have to put an annotation above each attribute of
//your class:
public class Category(){
int id;
String name;
List<CategoryBook> categoryBooks;
}
public class CategoryBook(){
int id;
String name;
}
public class SubCategory(){
//Based on your json I will assume the attribute of this class
// is a model that have a list of an object that have an id and a name
//and a list of subcategorybooks
}
public class SubCategoryBooks(){
//class attributes that you not mentioned in your json
}
Then you just need to parse your object from content using gson,
if you have some doubts about how to parse using Gson follow this tutorial
For insert into database separate, you already have your objects with getters and setters, for example
you can get the List<CategoryBook> from your CategoryModel, then your can insert this list
inside a separate table of your database.
Hope It's Help you
JSONObject jsonObject = new JSONObject();
jsonObject.put("category",loaddata());
public JSONObject loaddata(){
JSONObject jsonObject = new JSONObject();
jsonObject.put("id","1");
jsonObject.put("name","Education");
jsonObject.put("categorybooks",addcategorybooks());
jsonObject.put("subcategory","addsubcategory()");
return jsonObject;
}
public JSONArray addcategorybooks(){
JSONArray JsonArray = new JSONArray();
JSONObject jObj = new JSONObject();
jObj.put("id", "1");
jObj.put("name", "Foot Ball");
JsonArray.put(jObj);
return JsonArray;
}
public JSONArray addsubcategory(){
JSONArray JsonArray = new JSONArray();
JSONObject jObj = new JSONObject();
jObj.put("id", "1");
jObj.put("name", "Foot Ball");
jObj.put("subcategorybooks", addsubcategorybooks());
JsonArray.put(jObj);
return JsonArray;
}
public JSONArray addsubcategorybooks(){
JSONArray JsonArray = new JSONArray();
JSONObject jObj = new JSONObject();
jObj.put("id", "1");
jObj.put("name", "Foot Ball");
JsonArray.put(jObj);
return JsonArray;
}
If i understood you correctly, the main problem is to get java model object from json.
There are several ways to do it. The most common are:
Using built-in tools to operate with Json. In this case you get org.json.JSONObject and get values using it's methods. See details f.e. here
Using gson library. In this case you create model class and you can fill the object with one code line. smth like Category category = gson.fromJson(yourJsonString, Category.class); See details in official tutorial

Categories

Resources