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);
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..
1.I am having json object like this how can i get the access to all values in android
2.before anyone down voting that i want to say i have searched stackoverflow for similar examples but those examples contains JSONObject and then JSONArray
3.Here in my case everything is JSONObject so i'm little bit confused
{
"1":
{"sno":"10","latitude":"31.249441437085455","longitude":"75.70003598928452"},
"2":
{"sno":"11","latitude":"31.249398442090207","longitude":"75.70003397762775"}
}
This is how i made it to JSONObject
1.Below code returned me output like that which is all JSONObject
2.Is there any way to make "1" and "2" as JSONArray ?
$select_rows = "select sno,latitude,longitude from activities where username='$username'";
if ($result = mysql_query($select_rows)) {
$num_of_fields = mysql_num_fields($result);
$num_of_rows = mysql_num_rows($result);
$i = 0;
$j = 1;
while ($retrieved = mysql_fetch_array($result)) {
for ($i = 0; $i < $num_of_fields; $i++) {
$field_name = mysql_field_name($result, $i);
$object[$j][$field_name] = $retrieved[$field_name];
}
$j++;
}
echo json_encode($object);
}
Hope this may help you
JSONObject jsonObject=new JSONObject(result);
jsonObject=jsonObject.getJSONObject("1");
Double lat=jsonObject.getDouble("latitude");
Toast.makeText(getBaseContext(),""+ lat, Toast.LENGTH_LONG).show();
Better create a valid JSONArray to make things easier. When you create the JSON string , don't append the index. I believe your are reading the data from sqlite and generating the JSON string.
Also change the outer { (curly brace) to [ (square bracket) to represent as Array element. So your json string will be like this
[
{
"sno": "10",
"latitude": "31.249441437085455",
"longitude": "75.70003598928452"
},
{
"sno": "11",
"latitude": "31.249398442090207",
"longitude": "75.70003397762775"
}
]
Then , you can simply get its as JSONArray
JSONArray jsonArray = new JSONArray(jsonString);
And then read each element in array item
for(int index = 0;index < jsonArray.length(); index++) {
JSONObject jsonObject = jsonArray.getJSONObject(index);
}
To get one of your inner JSONObject elements, you'll need to get it from the outer one using getJSONObject(String key).
Sample code:
JSONObject item1 = myJson.getJSONObject("1");
//item1 now contains {sno:10,latitude:31.2...etc}
//now you can get the individual values out of the resulting JSON Object
//for example, getting the latitude
double lat = item1.getDouble("latitude");
Want Android Code For Following JSON Format...Bit Confused How to fetch value of array For Following Pattern..
{
"params": [
{
"answer_data_all": [
{
"id": "5",
"question_id": "14"
}
],
"form_data_all": [
{
"id": "1",
"name": "form 1"
}
]
}
]
}
You just have some nested JSONArray and JSONObject. Assuming you have this response in string format all you have to do is create JSONObject from that string and then extract what you need. As someone mentioned [ ] encloses JSONArray while { } encloses JSONObject
JSONObject mainObject = new JSONObject(stringResponse);
JSONArray params = mainObject.getJSONArray("params"); //title of what you want
JSONObject paramsObject = params.getJSONObject(0);
JSONArray answerData = paramsObject.getJSONArray("answer_data_all");
JSONArray formData = paramsObject.getJSONArray("form_data_all");
String id = formData.getJSONObject(0).getString("id");
You should be able to extract all the values doing something like this. Although I will say I think the formatting is odd. You're using single member arrays that just contain other objects. It would make much more sense to either use one array to hold all the object or just separate JSONObject. It makes it much easier to read and easier to parse.
Parsing a JSON is fairly simple. You could use GSON library by Google for example. Below is an example I wrote for your object/model:
class MyObject{
ArrayList<Params> params;
class Params {
ArrayList<AnswerData> answer_data_all;
ArrayList<FormData> form_data_all;
class AnswerData {
String id;
String question_id;
}
class FormData {
String id;
String name;
}
}
}
And then get an instance of your object with:
MyObject myObject = (MyObject) (new Gson()).toJson("..json..", MyObject.class);
JSONArray feed = feedObject.getJSONArray("params");
for(int i = 0; i<feed.length(); i++){
JSONArray tf = feed.getJSONArray(i);
for (int j = 0; j < tf.length(); j++) {
JSONObject hy = tf.getJSONObject(j);
String idt = hy.getString("id");
String name = hy.getString("name");
}
}
**NOTE: the 'feedObject' variable is the JSONObject you are working with..Although this your type of JSON feed is kinda mixed in terms of string names and all but this should do for now..
I am trying to read a list from JSON format into Android Java.
I can read children using getJSONarray(). But unable to read values of message or email.
Seems getJSONarray() doesnt work for what i want.
Yes, i am using getJSONObject on children to extract message. But how do i extract individual values after getting message array?
{
"children": [{
"message": ["message1","message2","message3"],
"email": ["email1",
"email2"]
}, {
"message": ["message1", "message2", "message3"],
"email": ["email1", "email2"]
}]
}
I know how to extract from:
{
"children": [{
"message1": "message___1"
"message2": "message___2"
"message3": "message___3"
}]
}
But not when it is all in a list.
What you need to do once you've got the JSONArray of "children" is to then extract the individual JSONObjects one by one like so:
for (int counter = 0; counter < childArray.length(); counter++) {
//Get the next item
JSONObject nextobj = childArray.getJSONObject(counter);
Then you can extract your message and email arrays from your nextobj variable. This is because each "message" and "email" is not directly accessible from your "children" JSONArray, they're wrapped up in JSONObjects
try the below code:
for(int i=0; i<childrenArray.length(); i++)
{
JSONObject childObj=childrenArray.getJSONObject(i);
JSONArray messageArray=childObj.getJSONArray("message");
for(int j=0; j<messageArray.length();j++
{
//here get value from messageArray.getString(j) or messageArray.getJSONObject(j), whichever applicable
}
JSONArray emailArray=childObj.getJSONArray("email");
for(int k=0; k<emailArray.length();k++
{
//here get value from emailArray.getString(k) or emailArray.getJSONObject(k), whichever applicable
}
}
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.