Append values to json object in android - android

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

Related

How to parse json data which has multiple jsonArrays in android?

I have JSON data like this,it is having multiple jsonArrays in it.how to parse this type of data?
{
"result":
[{
"site_name":"comenius",
"ws_url":"https://comenius-api.sabacloud.com/v1/",
"base_url":"https://comenius.sabacloud.com/",
"logo_url":"",
"Title":"",
"menu_items":[
{"item":
[{"id":"home1","label":"Home" }]
},
{"item":
[{"id":"enrol1","label":"Enrollment" }]
},
{"item":
[{"id":"transcripts1","label":"Completed Courses"}]
},
{"item":
[{"id":"goals1","label":"Goals"}]
},
{"item":
[{"id":"rprojects1","label":"Reference Projects"}]
},
{"item":
[{"id":"iwh1","label":"Internal Work History"}]
},
{"item":
[{"id":"ewh1","label":"EXternal Work History"}]
}
]
},{.....}
]
}
i need to parse the data and get the values of id,label ,i write some code to parse the data but it didnt work.
JSONObject subObj = new JSONObject(data2);
JSONObject innerObj1 = subObj.getJSONObject("result");
JSONObject subArrayObj = innerObj1.getJSONObject("menu_items");
for(int j =0;j < subArrayObj.length();j++) {
JSONObject innsersubObj = subArrayObj.getJSONObject("item");
String id = innsersubObj.getString("id");
String label = innsersubObj.getString("label");
Log.e("id",id);
Log.e("label",label);
}
How to parse the data any thing need to change in the code ?
You have to use JSONObject and JSONArray are different objects, you have to use correct class:
JSONArray resultArray = subObj.getJSONArray("result");
JSONObject firstItem = resultArray.getJSONObject(0);
JSONArray menuItems = firstItem.getJSONArray("menu_items");
etc.
JSONARRAY subArrayObj = innerObj1.getJSONARRAY("menu_items");
Since menu_items is returning an array..it should be collected in an array object..

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

Android - json parsing

I have a JSON as shown below:
{
"places": [{
"name": "Ankola",
"slug": "ankola",
"category": "beach",
"distance": "521",
"travel_time": "8 hrs, 2 mins",
"days": "3",
"latitude": "14.669456",
"longitude": "74.300952",
"weather": "Summer 21\u00b0-36\u00b0C, Winter 12\u00b0-35\u00b0C",
"todo": "Baskal gudda, Nadibag, Shedikuli, Keni, Belekeri",
"about": "Ankola is a small town surrounded by numerous temples. It is in line with Arabian sea. Ankola is famous for its native breed of mango called ishaad and for cashews harvesting.",
"image": [
"Cm5NXlq.jpg",
"9OrlQ9C.jpg",
"DRWZakh.jpg",
"dFKVgXA.jpg",
"5WO2nDf.jpg"
]
}]
}
I know how to fetch key - value pairs, but i dont know how to parse array inside json to form a string array(image - in my case)
To summarize i want something like this:
I have 5 image names under "image" tag, i want them in a string array. How can i do this?
Use :
JSONArray images = yourJSONObject.getJSONArray("image");
for(int i = 0; i < images.length(); i++){
String image = images.getString(i);
}
This should do the trick as I remember.
Here you go:
JSONArray ja = whatEverYourJsonObject.getJSONArray("image");
for(int i=0; i<ja.length(); j++){
String name = ja.getString(i);
}
You first have to convert the JSON string to a Java object (JSONObject). Then, you obtain your JSONArray and iterate over it.
Example:
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject (jsonString);
JSONArray images = itemObj.getJSONArray ("images");
int length = images.length ();
for (int i = 0; i < length; i++)
Log.d ("Image Filename", images.getString (i));
} catch (JSONException e) {
e.printStackTrace();
}
EDIT: Now I see that your JSON is invalid - you have an object for each image and that object contains only the value part of the data. An example of a valid images array would be as follows:
{
"image": [
"Cm5NXlq.jpg",
"9OrlQ9C.jpg",
"DRWZakh.jpg",
"dFKVgXA.jpg",
"5WO2nDf.jpg"
]
}
I would suggest:
Create your own class which describes your data structure defined
by those json object. As a last resort you can even generate Java
class based on JSON string - look at
jsongen
When you will have your own Java class (let's say MyClass) you can easily parse JSON to your generated Java class using GSON, like:
MyClass myClass = gson.fromJson(jsonString, MyClass.class);

how do i read id value using java language?

{
"id": "2345631223",
"name": "MyFbAcc",
"picture": "http://profile.ak.fbcdn.net/hprofile-ak-snc4 /373042_396504583708761_162084_s.jpg",
"link": "http://www.facebook.com/MyFbAcc",
"likes": 70,
"cover": {
"cover_id": 434873094856,
"source": "http://a3.sphotos.ak.fbcdn.net/hphotos-ak-snc7/s720x720/396014_493579484001270_1795_n.jpg",
"offset_y": 0
}
Normal Xml files I used to read xml parsing/DocumentBuilderFactory, which xml consists of tags, etc, but here all are represent in " ". how do I get read the id value?
id=2345631223. Any help most welcome?
Using JSON..
JSONObject object = new JSONObject(yourString);
String id = object.getString("id");
if i suppose you are making the JSON object with a String
String jString="{"name":"value"};
JSONObject jObject = new JSONObject(jString);
then you can retrieve the value form the name-value pairs like
String valueFromJSON= jObject.getString("name");

JSON array parsing in android

Here is my JSON object and i want to parse it in android project
{
"second": {
"versionInfo": "0.20.3-dev",
"compileDate": "Mon Mar 12 17:39:23 IST 2012",
"compileUser": "suraj",
"trackname": "tracker_localhost:localhost/127.0.0.1:48418"
},
"href": {
"versionInfo": "null",
"compileDate": "null",
"compileUser": "null",
"trackname": "null"
},
"first": {
"key": "['trackname','versionInfo','compileDate','compileUser']"
}
}
How to compile?
i want to first extract attributes of 'first' and using the attributes and then to extract parameters of 'second' using attributes of 'first'.
Basically it is done like that:
JSONObject jobj = new JSONObject(theString);
JSONObject first = jobj.getJSONObject("first");
JSONObject second = jobj.getJSONObject("second");
If you want more, take a look at the documentation of JSON classes for android.
Edit
Regarding the extraction of the array (in first->key):
String jStr = first.getString("key");
JSONArray jArr = new JSONArray(jStr);

Categories

Resources