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
Related
I want to remove json value from below json file .
This is my json object :
{
"Approximation": {
"name": "Approximation",
"description": [
"Approximation",
"Approximation",
"Approximation"
],
"video": [
"evideo/package1/maths/Approximation/349188_f2ba28819a74355a456ef91d95451b71/349188_f2ba28819a74355a456ef91d95451b71/349188.mpd",
"evideo/package3/maths/approxomation/396183_Approximation/396183_fcedf516e0f5c935d561d486058fa6e0/396183.mpd",
"evideo/package2/maths/approxomation/387010_01approximation/387010_949440b1082fea19faa7dcb4aebf0b43/387010.mpd"
]
}
}
and this is what I'm trying
Code :
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
jsonArr.remove(i);
children = new ArrayList<ChildrenEvent>();
et = new Events(jsonObj.optString("name"));
ct = new ChildrenEvent(jsonObj.optString("description"));
langs.add(et);
children.add(ct);
}
I am not sure what you are trying to achieve here. You don't need to remove the key "Approximation" to get the data.
This is how you parse this JSON.
{
"Approximation": {
"name": "Approximation",
"description": ["Approximation", "Approximation", "Approximation"],
"video": ["evideo/package1/maths/Approximation/349188_f2ba28819a74355a456ef91d95451b71/349188_f2ba28819a74355a456ef91d95451b71/349188.mpd", "evideo/package3/maths/approxomation/396183_Approximation/396183_fcedf516e0f5c935d561d486058fa6e0/396183.mpd", "evideo/package2/maths/approxomation/387010_01approximation/387010_949440b1082fea19faa7dcb4aebf0b43/387010.mpd"]
}
}
Code,
JSONObject mainObj = new JSONObject(json_string);
JSONObject appproxObj = mainObj.getJSONObject("Approximation");
// Parse name
String name = appproxObj.getString("name");
et = new Events(name);
langs.add(et);
// Parse descriptions
JSONArray descriptions = appproxObj.getJSONArray("description");
children = new ArrayList<ChildrenEvent>();
for (int i = 0; i < descriptions.length(); i++ ) {
String description = descriptions.getString(i);
ct = new ChildrenEvent(description);
children.add(ct);
}
Still if you need the JSON without key "Approximation", the variable appproxObj has the JSON without the key.
There is a method in JsonObject, that is remove(). It will help you to remove any key from jsonObject;
Use this:-
jsonObject.remove("key");
I am getting Json parsing
Here my java code
if(jsonstr!=null){
try{
JSONObject jsonResponse = new JSONObject(jsonstr);
/***** Returns the value mapped by name if it exists and is a JSONArray. ***/
/******* Returns null otherwise. *******/
JSONArray jsonproduct = jsonResponse.optJSONArray("products");
/*********** Process each JSON Node ************/
int lengthJsonArr = jsonproduct.length();
for (int i = 0; i < lengthJsonArr; i++) {
JSONObject c = jsonproduct.getJSONObject(i);
itemcode.add(c.get("Code").toString());
item.add(c.get("Name").toString());
quantity.add("");
category.add("CategoryCode");
}
Error is
org.json.JSONException: Value [{"categories":[{......................all json}]
My json is Like
[ { categories{[ "a":"s" "b":"g"
},
{ "a":"s" "b":"g"
}
]},
product{[ "a":"s" "b":"g"
},
{ "a":"s" "b":"g"
}
]} ]
MY Json web service url
[webservice][1]
Please Help Me How I can fix this problem
Thanks In Advance
Try that:
replace products to categories
try{
JSONObject jsonResponse = new JSONObject(jsonstr);
/***** Returns the value mapped by name if it exists and is a JSONArray. ***/
/******* Returns null otherwise. *******/
JSONArray jsonproduct = jsonResponse.optJSONArray("categories");
/*********** Process each JSON Node ************/
int lengthJsonArr = jsonproduct.length();
for (int i = 0; i < lengthJsonArr; i++) {
JSONObject c = jsonproduct.getJSONObject(i);
itemcode.add(c.get("Code").toString());
item.add(c.get("Name").toString());
quantity.add("");
category.add("CategoryCode");
}
try this,
if(jsonstr!=null){
try{
JSONArray jsonResponse = new JSONArray(jsonstr);
JSONObject jsonResponse = jsonResponse.get(0);
/***** Returns the value mapped by name if it exists and is a JSONArray. ***/
/******* Returns null otherwise. *******/
JSONArray jsonproduct = jsonResponse.getJSONArray("products");
/*********** Process each JSON Node ************/
int lengthJsonArr = jsonproduct.length();
for (int i = 0; i < lengthJsonArr; i++) {
JSONObject c = jsonproduct.getJSONObject(i);
itemcode.add(c.get("Code").toString());
item.add(c.get("Name").toString());
quantity.add("");
category.add("CategoryCode");
}
Your JSON is not valid.
You can use a online tool for checking: http://json.parser.online.fr/
Link for the JSON Syntax: http://www.w3schools.com/json/json_syntax.asp
EDIT:
Ok, now we have your real JSON, it's correct.
What about replacing JSONObject by JSONArray. Because your JSON is a Array.
Your JSON is not valid.
Maybe you were going for something like this?
{
"categories": [
{
"a": "s",
"b": "g"
},
{
"a": "s",
"b": "g"
}
],
"product": [
{
"a": "s",
"b": "g"
},
{
"a": "s",
"b": "g"
}
]
}
its because the json you are using is not valid.
and the parsing you are doing is not valid too
here is a good link to start off with android json parsing
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
This happening because your json is start with the jsonArray then why you take the jsonObject for that
[
{
"categories": [
{
"Code": "1001",
"Name": "ROOM LINEN",
"ShortName": "ROLN",
"DivisionCode": "10",
"SequenceNo": "3"
you should try #akash moradiya's code a given ans he is pointing to right way.
Try this..
JSONArray jsonarray = new JSONArray(jsonstr);
JSONObject jsonResponse = jsonarray.getJSONObject(1);
JSONArray jsonproduct = jsonResponse.getJSONArray("products");
for (int i = 0; i < jsonproduct.length(); i++) {
JSONObject c = jsonproduct.getJSONObject(i);
itemcode.add(c.getString("Code"));
item.add(c.getString("Name"));
quantity.add("");
category.add("CategoryCode");
}
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 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.