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");
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..
I'm currently making a bible verse app for android, and the problem I am having might be common, but I find it difficult to implement since I'm a beginner.
How will I get each information in a string from the json data sampled below ?
{
"book": "1 John",
"chapters": [{
"chapter": "1",
"verses": [{
"1": "That which was from the beginning, which we have heard, which we have seen with our eyes, which we have looked upon, and our hands have handled, of the Word of life;"
}, {
"2": "(For the life was manifested, and we have seen it, and bear witness, and shew unto you that eternal life, which was with the Father, and was manifested unto us;)"
}]
}]
If I were to get each data so that I can use it as a string or a list, should I use a code like the following ? How can I change the code so that it can get the data from the json ? I would love to hear from you!
JSONObject obj = new JSONObject(script);
JSONArray chapters = obj.getJSONArray("chapters");
ArrayList < HashMap < String, String >> formList = new ArrayList < HashMap < String, String >> ();
HashMap < String, String > m_li;
for (int i = 0; i < chapters.length(); i++) {
JSONObject jo_inside = chapters.getJSONObject(i);
String formula_value = jo_inside.getString("chapters");
String url_value = jo_inside.getString("verse");
}
Better representation of data would be like this.
{
"book": "1 John",
"chapters": [
{
"chapter": "1",
"verses": [
{
"1": "That which was from the beginning, which we have heard, which we have seen with our eyes, which we have looked upon, and our hands have handled, of the Word of life;"
},
{
"2": "(For the life was manifested, and we have seen it, and bear witness, and shew unto you that eternal life, which was with the Father, and was manifested unto us);"
}
]
}
]
}
As you can see we have two level of list which are represented by [ ] in JSON. I have also removed unnecessary complex JSON object.
JSONObject obj = new JSONObject(script);
JSONArray chaptersList = obj.getJSONArray("chapters");
ArrayList<HashMap<String, String>> chapterHash = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < chaptersList.length(); i++) {
JSONObject chapter = chaptersList.getJSONObject(i);
String chapterId = chapter.getString("chapter");
chapterHash.add(new HashMap<String, String>());
JSONArray versesList = chapter.getJSONArray("verses");
for(int j=0;j < versesList.length();j++){
JSONObject verse = versesList.getJSONObject(j);
for(int k = 0; k<verse.names().length(); k++){
String verseKey = verse.names().getString(k);
String verseContent = verse.getString(verseKey);
chapterHash.get(i).put(verseKey,verseContent);
}
}
}
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..
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);