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
Related
I have a JSONObject. I need to append some details to that.
Existing JSON
{
"class": {
"name": "first",
"language": "English"
}
}
and i need to append values to this like
{
"class": [{
"name": "first",
"language": "English"
}, {
"name": "first",
"language": "English"
}]
}
I'm not the first to ever say this,
But you should use JSONObject.put with the modified value, e.g
JSONObject main = new JSONObject();
// ...
main.put("Classes", newClasses);
You can't do that with your current object. You have to change the type of the JSONObject you're appending to. As noted in the comments, you actually just want to serialize an array of custom objects.
Therefore, create a JsonArray as described in this answer: JSONObject.append into object - result is nested array?
Java is not my first language, but maybe this will help you out:
//First create the name and language object
JSONObject nameLanguageObj = new JSONObject();
nameLanguageObj.add("name","first");
nameLanguageObj.add("language","English");
//Create the array to hold the objects
JSONArray arr = new JSONArray();
arr.put(nameLanguage);
//Create the full class object as you requested.
JSONObject classObj = new JSONObject();
classObj.put("class", arr);
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": "Metro 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 */);
}
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
My JSON file contains strings with the same keys but some of them doens't appear for some strings. For example:
{
"city": "CB1 2BH Cambridge",
"addr": "Devonshire Road 1",
"title": "Devonshire Arms",
"phone": "+44 1223 6610"
},
{
"city": "E8 1JH London",
"addr": "Amhurst Road 90",
"title": "Pembury Tavern",
"web": "http://www.individualpubs.co.uk/pembury/"
},
{
"web": "http://bandholmhotel.dk/",
"title": "Bandholm Hotel",
},
{
"city": "00100 Helsinki",
"addr": "Pohjoinen Rautatiekatu 23",
"title": "Helkan Baari",
"country": "FI"
},
How to correctly parse it in android?
Considering this is your JSONArray,
Try to do as following,
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jObj = (JSONObject) jsonProductArray.getJSONObject(i);
String city = jObj.optString("city", "cityDefaultValue");
String addr = jObj.optString("addr", "addDefaultValue");
String title = jObj.optString("title", "titleDefaultValue");
String phone = jObj.optString("phone", "phoneDefaultValue");
}
One possible solution can be to have a modal class and use Gson library to parse the Json.
You can set some default values in your modal class, for keys whose value is not found in Json
Create an model class with the key of the json and parse it to the model class using gson.
A a = gson.fromJson(jsonRes.toString(),A.class);
here A is your model class and a is the instance of A
You can use Gson library.
Create something like that
class SomeObjects {
#SerializedName("city")
private String mCity;
#SerializedName("addr")
private String mAddres;
...
}
and in then
SomeObject obj = new Gson.fromJson(jsonString, SomeObject.class);
You also can sirialize right into array
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");