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");
Related
I have been trying to extract array elements from my JSON, but unable to, so far.
I have the following JSON:
{
"Sample JSON": [{
"Title": "Title1",
"Audit": [{
"auditId": "01",
"type": "sampleType",
"auditText": "sampleText",
"answer": ["Ans1", "Ans2"]
},
{
"auditId": "02",
"type": "sampleType2",
"auditText": "sampleText2",
"answer": ["Ans1", "Ans2", "Ans3", "Ans4"]
}
]
},
{
"Title": "Title2",
"Audit": [{
"auditId": "03",
"type": "sampleType3",
"auditText": "sampleText3",
"answer": ["Ans1", "Ans2"]
},
{
"auditId": "04",
"type": "sampleType4",
"auditText": "sampleText4",
"answer": ["Ans1", "Ans2", "Ans3", "Ans4"]
}
]
}
]
}
I want to extract the array elements of the array 'answer'.
I get exception in the line indicated in comment in the method below:
public void getAudit(String myJSON) {
auditList = new ArrayList<AuditList>();
String title;
String auditId;
String type;
String auditText;
ArrayList<String> answer = new ArrayList<>();
try {
JSONObject jsonObj = new JSONObject(myJSON);
JSONArray jssArray = jsonObj.getJSONArray("Sample JSON");
int jsonArrLength = jssArray.length();
for (int i = 0; i < jsonArrLength; i++) {
JSONObject jsonChildObj = jssArray.getJSONObject(i);
title = jsonChildObj.getString("Title");
JSONArray jssArray1 = jsonChildObj.getJSONArray("Audit");
for (int i1 = 0; i1 < jssArray1.length(); i1++) {
JSONObject jsonChildObj1 = jssArray1.getJSONObject(i1);
type = jsonChildObj1.optString("type");
auditText = jsonChildObj1.optString("auditText");
auditId = jsonChildObj1.optString("auditId");
JSONArray jssArray2 = jsonChildObj1.getJSONArray("answer");
//Getting exception in above line
for (int j=0; j<jssArray2.length(); j++)
{
answer.add(jssArray2.get(j).toString()) ;
}
AuditList aList = new AuditList();
aList.setQuesId(auditId);
aList.setQuesText(auditText);
aList.setQuesTypw(auditType);
aList.setAnswer(answer);
aList.setCategoryName(title);
auditList.add(aList);
}
}
.
.
.
.
.
}
I found the exception occurring in the line indicated above using the debugger.
Couldn't find a way to extract array elements of the array 'answer'.
Please help.
if(!jsonChildObj1.get("answer").toString().equals("")){
JSONArray jssArray2 = jsonChildObj1.getJSONArray("answer");
for (int j=0; j<jssArray2.length(); j++)
{
answer.add(jssArray2.get(j).toString()) ;
}
}
The exception that occurred to you because of Empty Data (""). To Prevent this validate it and getJSONArray(). refer
The way I do this kind of stuff is by going to this link and then paste my json there and get my class. After that, you can go and add Gson to your gradle by adding this line to your build.gradle:
compile 'com.google.code.gson:gson:2.6.2'
Then just create an instance of the created class that you just created and convert json into your target class:
NewClass classObject = new Gson().fromJson(YOUR_JSON, NewClass.class);
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");
my problem is that i have an asp. web service .. and it gives me the following result when i invoke it :
[
{
"_OrderDetails": [
{
"ProductName": "FUCHS SUPER GT SAE 10W30 6X5 / FP10100010102",
"TotalAfterDiscount_Lc": "7500",
"MeasureUnitName": "كرتونة",
"TotalPrice_Lc": "7500",
"PricePerUnit_Lc": "75",
"Quantity": "100"
}
],
"Id": "274",
"OrderDate": "4/10/2014 12:00:00 AM",
"Number": "16",
"CustomerName": "الأسد",
"Note": ""
}
]
and in the main activity i do the following :
Gson gson = new Gson();
Log.e("Response", responseJSON);
if (responseJSON != null) {
try {
JSONObject jsonObj = new JSONObject(responseJSON);
//JSONArray jsonarr =new JSONArray();
// details=jsonObj.getJSONObject(0);
// Getting JSON Array node
details = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < details.length(); i++) {
JSONObject c = details.getJSONObject(i);
String product = c.getString(TAG_PRODUCT);
Log.e("prodeuct",product+"");
}
i see the response in the logcat correctly but when i try to get any object from the array i see a JSON exception it says :
JSON array can't be converted to JSON object !!!
please can anyone help me??
Because your json return jsonarray and you are try to access jsonobject.
Change your code:
if (responseJSON != null) {
try {
JSONArray jsonObj = new JSONArray(responseJSON);
// looping through All Contacts
for (int i = 0; i < jsonObj.length(); i++) {
// your code
}
Chang to JSONArray
if (responseJSON != null) {
try {
JSONArray array = new JSONArray(responseJSON)
}
http://jsonviewer.stack.hu/ use it to view your json and resolve it accordingly. you are using json array as json object.
use these:
JSONObject jsonObj = new JSONObject(responseJSON);
to
JSONArray jr = new JSONArray(responseJSON);
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