Filter JSONObject in JSONArray Android - android

How I filter this JSONArray that the JSONObject "name" contain "abcd"
{
"items":[{
"id":"082111",
"name":"abcd efgh"
}, {
"id":"082112",
"name":"abcd klmn"
}, {
"id":"082113",
"name":"klmn efgh"
}, {
"id":"082114",
"name":"abcd efgh"
}, {
"id":"082115",
"name":"efgh oprs"
}
]
}
And the result is must be
{
"items":[{
"id":"082111",
"name":"abcd efgh"
}, {
"id":"082112",
"name":"abcd klmn"
}, {
"id":"082114",
"name":"abcd efgh"
}
]
}
How I can get the result like that?
Should I convert the JSONArray to ArrayList, and filter when have converted to ArrayList, and convert again to JSONArray?
If yes, how i convert the JSONArray to ArrayList and filter it? And conver again to JSONArray?
Please give me samples code.

With the following code you'll get that which ever you required that is which are starting with the letters abcd like as you said.
JSONObject json = new JSONObject(jsonString);
JSONArray jData = json.getJSONArray("items");
for (int i = 0; i < jData.length(); i++) {
JSONObject jo = jData.getJSONObject(i);
if ((jo.getString("name")).startsWith("abcd", 0)) {
Log.i("Name is ", jo.getString("name"));
}
}

Related

Not able to extract array elements from JSON in android

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);

android json parsing error - JSONArray cannot be converted JSONObject

i am converting a xml content into JSON content and the content is as follows
{
"response":
{
"seatlist":
{
"seat":
{
"balance":85694.6,"num":12
},
"seat":
{
"balance":85694.6,"num":12
}
},
"userid":"8970ca285d9c4e4d",
"seatnum":12,
"session":"online"
}
}
I am able to get the userid and seatnum in the following way
JSONObject response = json.getJSONObject("response");
out.setUserid(response.getString("userid"));
out.setBalance(Double.valueOf(response.getString("balance")));
Now the problem is i need to parse the following content and need to get "num" value
"seatlist":
{
"seat":
{
"balance":85694.6,"num":12
},
"seat":
{
"balance":85694.6,"num":12
}
}
here is my code i am using
JSONObject objList = response.getJSONObject("seatlist");
String n = String.valueOf(objList.getJSONObject("seat"));
if(objList.getJSONObject("seat").get("userId").equals(userId))
{
String num = String.valueOf(objList.getJSONObject("seat").get("num"));
out.setSeatNum(Integer.valueOf(num));
}
if i have one seat value i am able to get "num" value else i am getting JSON exception
Pls give me a suggestion in this.....
You want to get a JSONArray in an JSONObject. That is not possible.
Get the Array and then iterate through the array to get the objects:
JSONObject objList = response.getJSONArray("seatlist");
for(int i = 0, i<objList.lenght(); i++){
JSONObject json = objList.get(i);
}
{
"response":
{
"seatlist":
{
"seat":
{
"balance":85694.6,"num":12
},
"seat":
{
"balance":85694.6,"num":12
}
},
"userid":"8970ca285d9c4e4d",
"seatnum":12,
"session":"online"
}
}
means an object with an object called response. this contains an object called seatlist. this contains 2 objects called seat (but this is wrong! this should be an array!). and so on..
to read this you can use
JSONObject json = new JSONObject(yourresponse);
JSONObject response = json.getJSONObject("response");
JSONObject seatlist = response.getJSONObject("seatlist");
JSONObject userid = response.getJSONObject("userid");
JSONObject seatnum = response.getJSONObject("seatnum");
JSONObject session = response.getJSONObject("session");
now seatlist contains.
{
"seat":
{
"balance":85694.6,"num":12
},
"seat":
{
"balance":85694.6,"num":12
}
}
which is wrong, since it contains 2 elements with same name. Now you can either call it by index like this:
JSONObject seat1 = seatlist.getJSONObject(1);
JSONObject seat2 = seatlist.getJSONObject(2);
seat1.getString("balanace"); seat1.getInt("num");
or you can iterate through the JSONObject.
At least it should be an Array instead of JSONOBject.
This means it should look like this.
{
"response": {
"seatlist": [
"seat":
{
"balance":85694.6,"num":12
},
"seat":
{
"balance":85694.6,"num":12
}
],
"userid":"8970ca285d9c4e4d",
"seatnum":12,
"session":"online"
}
}

Error in parsing Json string Android

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");
}

is my JSON response correct? and why i see this exception when i try to retrieve it?

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);

parsing json 2 arrays (embbeded ) in android

I'm trying to find the value in jsonObject distance (which is 10194)
{
"destination_addresses" : [ "Burnaby, BC, Canada" ],
"origin_addresses" : [ "Vancouver, BC, Canada" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "10.2 km",
"value" : 10194
},
"duration" : {
"text" : "19 mins",
"value" : 1118
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I wrote this code but it gives me null
rows = jObj.getJSONObject(TAG_ROWS);
JSONArray elements = new JSONArray (rows.getString(TAG_ELEMENTS));
for (int i=0; i<elements.length();i++){
JSONObject obj = elements.optJSONObject(i);
JSONObject distance = obj.getJSONObject(TAG_DISTANCE);
value= distance.getString(TAG_VALUE);
any idea ??
You gonna have to do something as below
try {
JSONObject jsonObj = new JSONObject(YOUR-JSON-STRING-HERE);
String destination = jsonObj.getString("destination_addresses");
// printing the destination and checking wheather parsed correctly
Log.v("Destination", destination);
JSONArray jarRow = jsonObj.getJSONArray("rows");
for(int i=0;i<jarRow.length(); i++){
// creating an object first
JSONObject ElementsObj = jarRow.getJSONObject(i);
// and getting the array out of the object
JSONArray jarElements = ElementsObj.getJSONArray("elements");
for(int j=0; j<jarElements.length(); j++){
JSONObject distanceObj = jarElements.getJSONObject(j).getJSONObject("distance");
String distanceStr = distanceObj.getString("value");
Log.v("finally getting distance : ", distanceStr);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
here is a screen shot from DDMS
According to your JSON, even rows is of the type JSONArray, but you're fetching rows, this way
rows = jObj.getJSONObject(TAG_ROWS);
Hence, the problem.
You need to fetch rows like this:-
JSONArray rows = jObj.getJSONArray(TAG_ROWS);
The object 'rows' must be typed JSONArray since what it contains is an array. After that you must do another for and get the other array that is 'elements' and then do the loop for the second array. You must get something like:
rows = jObj.getJSONArray(TAG_ROWS);
for (int i=0; i<rows.length();i++){
JSONArray elements = new JSONArray (rows.getString(TAG_ELEMENTS));
for (int j=0; j<elements.length();j++){
JSONObject obj = elements.optJSONObject(j);
JSONObject distance = obj.getJSONObject(TAG_DISTANCE);
value= distance.getString(TAG_VALUE);
}
}

Categories

Resources