How to retrieve a multidimensional array using json object? - android

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 */);
}

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

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

Fetch value from JSON in android

I am sending request to the server and it gives me a response and giving data in JSON formats, now i want to fetch some specific value from that JSON format, so hot to do it.
{
"education": [
{
"school": {
"id": "2009305",
"name": "FG boys public high school Bannu Cantt "
},
"type": "High School"
},
{
"school": {
"id": "109989",
"name": "University of Engineering & Technology"
},
"type": "College"
}
],
"id": "xxxxxxx"
}
Now i need the school names from this xml,
Try this..
You response is in Json format not xml.
JSONObject json = new JSONObject(response);
JSONArray education = json.getJSONArray("education");
for(int i = 0; i < education.length(); i++){
JSONObject con_json = education.getJSONObject(i);
String school_type = con_json.getString("type");
JSONObject school_json = con_json.getJSONObject("school");
String school_name = school_json.getString("name");
}
It is not XML. it is completely in Json Standard format.
first build a JSONobject from your data:
JSONObject jsonObj = new JSONObject(result); //result = your Data String in fetched from server
then you cab retrieve what you want using its key. for example:
jsonObj.getString("id"); // it returns "xxxxxxx". as is in your data

Having trouble accessing object in JSON

I am trying to access the "display_name" object within the following JSON and I cannot seem to grab it. The example JSON is below.
{
"streams": [
{
"broadcaster": "fme",
"_id": 5019229776,
"preview": "http://static-cdn.jtvnw.net/previews-ttv/live_user_zisss-320x200.jpg",
"game": "Diablo III",
"channel": {
"mature": null,
"background": "http://static-cdn.jtvnw.net/jtv_user_pictures/zisss-channel_background_image-06a9d8c1113e5b45.jpeg",
"updated_at": "2013-03-04T05:27:27Z",
"_id": 31795858,
"status": "Barb sets giveaway and making 500m DH set... Join Zisspire, earn Zeny, collect prizes!",
"logo": "http://static-cdn.jtvnw.net/jtv_user_pictures/zisss-profile_image-502d7c865c5e3a54-300x300.jpeg",
"teams": [ ],
"url": "http://www.twitch.tv/zisss",
"display_name": "Zisss",
"game": "Diablo III",
"banner": "http://static-cdn.jtvnw.net/jtv_user_pictures/zisss-channel_header_image-997348d7f0658115-640x125.jpeg",
"name": "zisss",
"video_banner": null,
"_links": {
"chat": "https://api.twitch.tv/kraken/chat/zisss",
"subscriptions": "https://api.twitch.tv/kraken/channels/zisss/subscriptions",
"features": "https://api.twitch.tv/kraken/channels/zisss/features",
"commercial": "https://api.twitch.tv/kraken/channels/zisss/commercial",
"stream_key": "https://api.twitch.tv/kraken/channels/zisss/stream_key",
"editors": "https://api.twitch.tv/kraken/channels/zisss/editors",
"videos": "https://api.twitch.tv/kraken/channels/zisss/videos",
"self": "https://api.twitch.tv/kraken/channels/zisss",
"follows": "https://api.twitch.tv/kraken/channels/zisss/follows"
},
"created_at": "2012-07-01T21:09:58Z"
},
"name": "live_user_zisss",
"viewers": 775,
"_links": {
"self": "https://api.twitch.tv/kraken/streams/zisss"
}
}
],
"_links": {
"summary": "https://api.twitch.tv/kraken/streams/summary",
"followed": "https://api.twitch.tv/kraken/streams/followed",
"next": "https://api.twitch.tv/kraken/streams?channel=zisss%2Cvoyboy&game=Diablo+III&limit=100&offset=100",
"featured": "https://api.twitch.tv/kraken/streams/featured",
"self": "https://api.twitch.tv/kraken/streams?channel=zisss%2Cvoyboy&game=Diablo+III&limit=100&offset=0"
}
I start with:
JSONArray array = getJSONArray("streams");
JSONObject object = array.getJSONObject(4); // channel is entry 4 in array
String name = object.getString("display_name");
I'm not sure what I'm doing wrong here. With a more filled out JSON with multiple "channel" entries, I'm not sure how to handle it. I was thinking something like this?
String[] name = new String[array.length()];
JSONArray array = getJSONArray("streams");
for(int i = 0; i < array.length(); i++) {
if(array[i].equals("channel")
name[i] = array.getString("display_name");
I'm sure that last part is crude, and probably quite off from what it should be, but I'm not sure how to handle this.
Based on your JSON you have to do the following
JSONArray array = getJSONArray("streams");
JSONObject object = array.getJSONObject(0);
object = object.getJSONOBject("channel")
String name = object.getString("display_name");
The first item in you json array holds the channel object which contains the data you are looking for.
Channel is not the 4th item in your JSONArray but a nested object within the first. You have to be careful to follow the [] and {} brackets when parsing JSON because JSONObjects can contain multiple nested sub-objects and arrays.
JSONObject mainJsonObject = new JSONObject(json_string);
JSONArray array = mainJsonObject.getJSONArray("streams");
JSONObject channelObject = array.getJSONObject(0).getJSONOBject("channel")
String displayName = channelObject.getString("display_name");

Categories

Resources