I have JSON data like this:
"books": [
{
"rating": {},
"subtitle": "",
"author": [
"The OReilly Java Authors"
],
"pubdate": "2003-9",
"tags": [],
"origin_title": "",
…… …… …… …… … …
and I want get the author data,some "author"data has more than one author,but I just confused weather I could parse it like this:
JSONArray jsonbooks = mess.getJSONArray("books");
for(blabla){
JSONObject obj = jsonbooks.getJSONObject(i);
obj.getJSONArray("author").get(1):
or
JSONArray jsonbooks = mess.getJSONArray("books");
for(blabla){
JSONObject obj = jsonbooks.getJSONObject(i);
obj.getString("author");
sencond way,I could get the data like"["author,blabla "],I want get rid off [" "],and I need more string processing,if there a better way looks like the first way?
First one is right just one change obj.getJSONArray("author").getString(0):
JSONArray jsonbooks = mess.getJSONArray("books");
for(blabla){
JSONObject obj = jsonbooks.getJSONObject(i);
obj.getJSONArray("author").getString(0):
Since author is an array therefore first convert that into jsonArray
JSONArray jsonAuthor = mess.getJSONArray("author");
then String author = jsonAuthor.get(0); //this will give you -> The OReilly Java Authors
Hope this helps:
JSONArray jsonAuthorNode = booksJsonObject.optJSONArray("author");
int jsonArrLen = jsonAuthorNode.length();
for(int j=0;j<jsonArrLen;j++)
{
String authorName = jsonAuthorNode.get(j);
}
Related
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..
So I am receiving a JSON array in an httpresponse. The array consists of the following objects/variables.
{"sessid":"vxkEXkMBUmBByESRlvaxrxSaFTfhDqd8","session_name":"SESS88cdfb2f1c420898","user":{"uid":"60","name":"abc","theme":"","signature":"","signature_format":"filtered_html","created":"13082976","access":"1386287","login":1386211,"status":"1","timezone":null,"language":"","picture":null,"data":{"mimemail_textonly":0},"roles":{"2":"authenticated user","5":"centre user"},"field_centre_reference":{"und":[{"nid":"256"}]},"field_first_name":{"und":[{"value":"web","format":null,"safe_value":"web"}]},"field_surname":{"und":[{"value":"services","format":null,"safe_value":"services"}]},"bounce_mail_blocked":false,"force_password_change":"0"}}
Now I want to receive all these objects/strings in separate variables. Like i want to store the "sessid" in a variable String session_id. And so on. I can get the first two (i.e. sessid and session_name) in a simple way with the help of the following code.
response = client.execute(httppost);
BasicResponseHandler handler = new BasicResponseHandler();
String data = handler.handleResponse(response);
jObj = new JSONObject(data);
sessid = jObj.getString("sessid");
Log.d("sessid obj", sessid);
session_name = jObj.getString("session_name");
Log.d("session_name", session_name);
But since I am a noob at Android, I don't know how to get the rest of the data to be saved in variables. The upcoming data cannot be saved in a simple way.
Try with this:
JSONObject j_user = jObj.getJSONObject("user");
String uid = j_user.getString("uid");
...
//And so on with the rest of the fields
{ // json object node
"sessid": "vxkEXkMBUmBByESRlvaxrxSaFTfhDqd8",
"session_name": "SESS88cdfb2f1c420898",
"user": { // json object user
"uid": "60", // string
"name": "abc",
"theme": "",
"signature": "",
"signature_format": "filtered_html",
"created": "13082976",
"access": "1386287",
"login": 1386211,
"status": "1",
"timezone": null,
"language": "",
"picture": null,
"data": { // json object data
"mimemail_textonly": 0 //string
},
....// rest of the json
{ represents json object node
[ represents json array node
To parse
JSONObject jObj = new JSONObject(load());
String sessid = jObj.getString("sessid");
Log.d("sessid obj", sessid);
JSONObject user = jObj.getJSONObject("user");
String uid = user.getString("uid");
Log.d("sessid obj", uid);
To parse data
"data": {
"mimemail_textonly": 0
},
JSONObject data= user.getJSONObject("data");
Log.i(".......",""+data.getString("mimemail_textonly"));
To parser field_centre_reference
"field_centre_reference": { // json object field_centre_reference
"und": [ // json array und
{ // json object node
"nid": "256" //string
}
]
},
JSONObject field= user.getJSONObject("field_centre_reference");
JSONArray jr = field.getJSONArray("und");
JSONObject jb1 = (JSONObject) jr.get(0);
Log.i(".......",""+jb1.getString("nid"));
Check out JacksonParser library, it provides annotations which make your work so easy. And it is one of fastest parsing libraries... You can have it here
Edit:
As an example you can take a look at one of my previous question JacksonParser databind and core cause "Found duplicate file for APK"?
You should notice that the JSON you received is a nested JSON. It is like a Map that one of the value of Map is also a Map.
In your case, there is a JSONObject contains sessid and session_name while is only string, but the "user" is also a JSONObject, so you can parse it level by level.
For more details, you can read http://www.vogella.com/articles/AndroidJSON/article.html
Try this..
Getting
"user": {
"uid": "60",
JSONObject obj_user = jObj.getJSONObject("user");
String uid = obj_user.getString("uid");
"user": {
"uid": "60",
"data": {
"mimemail_textonly": 0
}
JSONObject obj_data = jObj.getJSONObject("data");
String mimemail_textonly = obj_user.getString("mimemail_textonly");
JSONObject obj_roles = jObj.getJSONObject("roles");
String two = obj_roles.getString("2");
"field_centre_reference": {
"und": [
{
"nid": "256"
JSONObject obj_field_centre_reference = jObj.getJSONObject("field_centre_reference");
JSONArray ary_und = obj_field_centre_reference.getJSONArray("und");
JSONObject objve = ary_und.getJSONObject(0);
String nid= objve.getString("nid");
im trying to get data from the site which have mongodb as their database and CI ,i make simple script to make json encode output from the site and the output is like :
{
"mko680": {
"_id": {
"$id": "515be1807bfb8b1d0d000000"
},
"channel": [
"channel a",
"subchannel a"
],
"channel_id": 227,
"id": "mko680",
},
"mkv002": {
"_id": {
"$id": "515b32407bfb8b1d0d000000"
},
"channel": [
"channel a",
"subchannel b"
],
"channel_id": 232,
"id": "mkv002",
}
}
i try to parse that output in my android project like this
JSONArray obj = new JSONArray(outputlike o);
for (int i = 0; i < obj.length(); i++) {
JSONObject json_data = obj.getJSONObject(i);
Log.i("test",json_data.getString("channel_id"));
}
the logcat said org.JSON.Mismatch
any clue for which is json/my code that not right ?
thanks , and sory for my bad question hope you understand
UPDATED :
now i change it to json object like :
JSONObject arr = new JSONObject(bufstring);
for (int i = 0; i < arr.length(); i++) {
Log.i("test",arr.getString("channel_id"));
}
but the logcat now said , no value for channel_id, but it sure there is channel_id in that output, any clue ?
The data you receive is of the type JSONObject and not JSONArray. Therefore, you need to parse your json data like this:-
String jsonStr = "..."; //Your JSONString
JSONObject obj = new JSONObject(jsonStr);
JSONObject mkObj = obj.getJSONObject("mko680");
String channelId = mkObj.getString("channel_id");
Your return data is Jsonobject not an JsonArray.
So, you can create JsonObject,
JSONObject obj = new JSONObject(outputlike o);
thank all based on your answer i have figured it out, at first i got difficult to get dynamic key for getting the right object i use below code to solved it, dont think its the good one but i use this in temporary
JSONObject arr = new JSONObject(bufstring);
Iterator keys = arr.keys();
while(keys.hasNext()) {
String ambilKey = (String)keys.next();
JSONObject AmbilObject = arr.getJSONObject(ambilKey);
Log.i("test",AmbilObject.toString());
}
thanks for all suggestion, you're rock :D
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);
I have JSON object as follows:
[
{
"Project": {
"id": "1",
"project_name": "name"
},
"AllocationDetail": [
{
"id": "1",
"project_id": "1",
"team_name": "ror",
"week_percentage_work": "50",
"in_today": "1",
"actual_hours": "30",
"remaining_hours": "100",
"time_difference": null,
"created": "2012-01-13 15:48:33",
"modified": "2012-01-13 15:48:33"
},
{
"id": "2",
"project_id": "1",
"team_name": "php",
"week_percentage_work": "40",
"in_today": "2",
"actual_hours": "50",
"remaining_hours": "100",
"time_difference": null,
"created": "2012-01-13 15:49:40",
"modified": "2012-01-13 15:49:40"
}
]
}
]
I want to parse data in android and store it into DB, but i m getting confused in Jsonobject
thanks
the best JSON Tutorial i have seen, I leared json parsing from this tutorial, hope it will help
The following is a snippet code for parsing your json string. Kindly go through it:
String response = <Your JSON String>;
String Project = null;
String AllocationDetail = null;
try {
JSONArray menuObject = new JSONArray(response);
for (int i = 0; i< menuObject.length(); i++) {
Project = menuObject.getJSONObject(i).getString("Project").toString();
System.out.println("Project="+Project);
AllocationDetail = menuObject.getJSONObject(i).getString("AllocationDetail").toString();
System.out.println("AllocationDetail="+AllocationDetail);
}
JSONObject jsonObject = new JSONObject(Project);
String id = jsonObject.getString("id");
System.out.println("id="+id);
String project_name = jsonObject.getString("project_name");
System.out.println("project_name="+project_name);
JSONArray jArray = new JSONArray(AllocationDetail);
for (int i = 0; i< jArray.length(); i++) {
String team_name = jArray.getJSONObject(i).getString("team_name").toString();
System.out.println("team_name="+team_name);
String week_percentage_work = jArray.getJSONObject(i).getString("week_percentage_work").toString();
System.out.println("week_percentage_work="+week_percentage_work);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
There are two ways for parsing JSON
Google GSON
JSON
When your content of JSON is too complex and long enough you can prefer usin GSON its much easier to maintain than JSON parsing each value manually.
Use jsonlint.com to read your json better. It appears that the json that you have copied here is invalid.
String response = <Your JSON String>; // add your Json String here
response = response.replace("[","").replace("]",""); // Just remove all square braces
JSONObject json = new JSONObject(response); //Convert the Json into Json Object
JSONObject jProject = json.getJSONObject("Project"); // get your project object
String project_id = jProject.getString("id"); // Get the value of Id
String project_name = jProject.getString("project_name"); // get the value of Project_name
The above code can be use many times as you want to parse the Json.
I know its too late, but It may help many people who are trying to find the same answer.
I was trying to find the same solution, but it was too hard to use the Accepted answer because of too many lines of codes, But I got the same results with hardly few lines of codes.