The data on server I want to retrieve, data in JSON format but problem is that I want to retrieve only data having specific CHEF_NAME from JSON array.I am using Android Studio.
JSON Array
[{"status":"Success","recpie":[{"id":"162","image":"1580130013.png","cat_id":"17","name":"Tikka Boti Mix Recipe","chef_name":"Mehran","link":"https:\/\/www.youtube.com\/watch?v=sbPNGHIOpQY","uvlink":"","like":"2","view":"227"},{"id":"168","image":"1580211123.png","cat_id":"17","name":"Seekh Kabab Paratha Roll Recipe","chef_name":"Mehran","link":"https:\/\/www.youtube.com\/watch?v=q36Syxhjg3o","uvlink":"","like":"19","view":"158"},{"id":"176","image":"recipe_1583154151.jpg","cat_id":"17","name":"Windows","chef_name":"Imran Ahmed","link":"","uvlink":"","like":"2","view":"119"},{"id":"190","image":"recipe_1584214019.jpg","cat_id":"17","name":"Chicken Broast","chef_name":"Imran Developer","link":"","uvlink":"http:\/\/billing.synctechsol.com\/video\/VID-20200112-WA0020.mp4","like":"3","view":"108"},{"id":"161","image":"1580309239.png","cat_id":"14","name":"Sindhi Biryani Mix Recipe","chef_name":"Mehran","link":"https:\/\/www.youtube.com\/watch?v=OUG7gYTrnEk","uvlink":"","like":"4","view":"104"},{"id":"182","image":"recipe_1584126527.jpeg","cat_id":"17","name":"Broast","chef_name":"Imran Developer","link":"","uvlink":"","like":"1","view":"64"},{"id":"198","image":"recipe_1584737360.jpeg","cat_id":"17","name":"Distribution Board","chef_name":"Imran Ahmed","link":"","uvlink":"http:\/\/billing.synctechsol.com\/video\/VID-20200219-WA0035.mp4","like":"7","view":"60"},{"id":"191","image":"recipe_1584260119.png","cat_id":"17","name":"ggbvn","chef_name":"Imran Developer","link":"","uvlink":"http:\/\/billing.synctechsol.com\/video\/VID-20200315-WA0001.mp4","like":"1","view":"58"},{"id":"163","image":"1580134470.png","cat_id":"15","name":"Achar Gosht Mix Recipe","chef_name":"Mehran","link":"https:\/\/www.youtube.com\/watch?v=5EQWOSRpzHg","uvlink":"","like":"8","view":"54"},{"id":"101","image":"1580210522.png","cat_id":"12","name":"Fish Fry Mix Recipe","chef_name":"Mehran","link":"https:\/\/www.youtube.com\/watch?v=GeSloGLoPMk","uvlink":"","like":"9","view":"50"},{"id":"178","image":"recipe_1583407824.jpg","cat_id":"17","name":"uhnbj","chef_name":"hi igh","link":"","uvlink":"","like":"0","view":"47"},{"id":"177","image":"recipe_1583234674.jpeg","cat_id":"17","name":"Kabuli Pulao","chef_name":"Imran Ahmed","link":"","uvlink":"","like":"0","view":"46"}]}]
Java Code
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String status = jsonObject.getString("status");
if (status.equals("Success")) {
JSONArray recipe = jsonObject.getJSONArray("recpie");
Log.e("Lenght", String.valueOf(recipe.length()));
for (int i = 0; i < recipe.length(); i++) {
JSONObject jsonObject1 = recipe.getJSONObject(i);
SearchGetSet searchGetSet = new SearchGetSet();
String id = jsonObject1.getString("id");
String image = jsonObject1.getString("image");
String cat_id = jsonObject1.getString("cat_id");
String name = jsonObject1.getString("name");
String chef_name = jsonObject1.getString("chef_name");
String link = jsonObject1.getString("link");
String uvlink = jsonObject1.getString("uvlink");
String like = jsonObject1.getString("like");
String view = jsonObject1.getString("view");
searchGetSet.setId(id);
searchGetSet.setRec_name(name);
searchGetSet.setRec_image(image);
searchGetSet.setLikes(like);
searchGetSet.setCat_id(cat_id);
searchGetSet.setChef_name(chef_name);
searchGetSet.setLink(link);
searchGetSet.setUVlink(uvlink);
searchGetSet.setView(view);
searchList.add(searchGetSet);}}
Create and add your searchGetSet object only if the chef_name is matching the name you're searching.
My guess is (I don't know Java), you've to use a simple if-statement, while looping :
for (int i = 0; i < recipe.length(); i++) {
JSONObject jsonObject1 = recipe.getJSONObject(i);
SearchGetSet searchGetSet = null; // Do not create your searchGetSet() object yet.
String chef_name = jsonObject1.getString("chef_name");
// Check the chef's name is 'John'.
if (chef_name.equals('John')) {
String id = jsonObject1.getString("id");
String image = jsonObject1.getString("image");
String cat_id = jsonObject1.getString("cat_id");
String name = jsonObject1.getString("name");
// ...
searchGetSet = new SearchGetSet();
searchGetSet.setId(id);
searchGetSet.setRec_name(name);
searchGetSet.setRec_image(image);
// ...
// Let's add the result we have found.
searchList.add(searchGetSet);
}
}
Related
I have a JSON string and U want to get the name and add fields. I've tried to use several libraries and follow many tutorials, but was unsuccessful.
I thing my problem is that i have several arrays together...
inputLine =
{"posts":[
{"post":{
"name":"name1",
"add":"add1"}},
{"post":{
"name":"name2",
"add":"add2"}}
]
}
JSONObject obj_posts = new JSONObject(inputLine);
JSONArray menuitemArray = obj_posts.getJSONArray("posts");
JSONObject obj_post = new JSONObject(menuitemArray.getJSONObject(0).toString());
JSONObject menuitem = obj_post.getJSONObject("post");
JSONArray obj_post1 = menuitem.names();
At this point I can only access the key name and add, not the values.
JSONObject obj_posts = new JSONObject(inputLine);
JSONArray menuitemArray = obj_posts.getJSONArray("posts");
JSONObject obj_post = menuitemArray.getJSONObject(0);
JSONObject menuitem = obj_post.getJSONObject("post");
String postName = menuItem.getString("name");
String postAdd = menuItem.getString("add");
The below code should work:
System.out.println(menuitem.get(obj_post1.getString(0)));//Output name1
System.out.println(menuitem.get(obj_post1.getString(1)));//Output add1
You need to import "org.json.JSONArray" , " org.json.JSONException", "org.json.JSONObject"
Also throws JSONException.
String obj_post1_name = "";
String obj_post1_add = "";
String obj_post2_name = "";
String obj_post2_add = "";
String inputLine =
" {\"posts\":[{\"post\":{\"name\":\"name1\",\"add\":\"add1\"}},{\"post\":{\"name\":\"name2\",\"add\":\"add2\"}}]}";
JSONObject obj_posts = new JSONObject(inputLine);
JSONArray menuitemArray = obj_posts.getJSONArray("posts");
JSONObject obj_post1 =(menuitemArray.getJSONObject(0));
JSONObject obj_post2 =(menuitemArray.getJSONObject(1));
JSONObject menuitem = obj_post1.getJSONObject("post");
JSONObject menuitem2 = obj_post2.getJSONObject("post");
obj_post1_name= menuitem.getString("name");
obj_post1_add= menuitem.getString("add");
obj_post2_name= menuitem2.getString("name");
obj_post2_add= menuitem2.getString("add");
or you can use loop after:
JSONArray menuitemArray = obj_posts.getJSONArray("posts");
JSONObject obj_posts;
JSONObject menuitem;
for(int i=0;i<menuitemArray.length();i++){
obj_posts= menuitemArray.getJSONObject(i);
menuitem = obj_post1.getJSONObject("post");
menuitem.getString("name");
menuitem.getString("add");
}
I'm trying to parse a json string/array to an object list. jsonString is the raw string which I try to make into a jsonArray at the moment like so:
List<Drink> drinks = new ArrayList<Drink>();
JSONArray jsonArr = new JSONArray(jsonString);
the string is:
[{"alcohol":"Vodka","date":"2014-04-25T22:04:51","units":3.0},
{"alcohol":"Beer","date":"2014-04-25T21:44:26","units":3.0}]
I don't really know how to progress from here,
any help would be awesome :)
You can iterate through the JSONArray and add to your drinks List like so:
for (int i=0; i<jsonArr.length(); i++) {
JSONObject jsonDrink = jsonArr.getJSONObject(i);
String alcohol = jsonDrink.getString("alcohol");
String date = jsonDrink.getString("date");
double units = jsonDrink.getDouble("units");
Drink drink = new Drink();
// initialize drink object values here or in constructor (don't know what this class has)
drinks.add(drink);
}
Iterate through the JSONArray, retrieve each JSONObject and call the appropriate Drink constructor from the object's attributes:
List<Drink> drinks = new ArrayList<Drink>();
JSONArray jsonArr = new JSONArray(jsonString);
int len = jsonArr.length();
for (int i = 0; i < len; ++i) {
JSONObject obj = jsonArr.getJSONObject(i);
String alcohol = obj.getString("alcohol");
String date = obj.getString("date");
double units = obj.getDouble("units");
Drink drink = new Drink(alcohol, date, units);
drinks.add(drink);
}
Of course, you may need to parse the date or do other data conversions before constructing your Drink object.
JSONArray has toList() method. see https://stleary.github.io/JSON-java/org/json/JSONArray.html#toList-- (I assume you use JSONArray form org.json)
your code should be like this
import org.json.JSONArray;
List<Drink> drinks = new JSONArray(jsonString).toList();
I have a JSON Object which converted into String and saved into database .But when i am trying to get it back it is throwing exception.My object is something like that...
{"COLUMN":["Type","Sub Type","F.P.","P.P.","Process","Due To Start"]}
How can we get the data back in Normal form?
My Java Code is.....
JSONObject obj = new JSONObject();
JSONArray the_json_array = obj.getJSONArray(userReorderOption);
int size = the_json_array.size();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
arrays.add(another_json_object);
}
And Exception i am getting....
net.sf.json.JSONException: JSONObject["{\"TASKLIST_COLUMN_REORDER\":[\"Type\",\"Sub Type\",\"F.P.\",\"P.P.\",\"Process\",\"Due To Start\"]}"] is not a JSONArray.
And this is java Code how i am creating JSON Object and saving into database...
String userReorderSelection;
Set set = new LinkedHashSet(userReorderSelection);
JSONObject json = new JSONObject();
json.accumulate("COLUMN", set);
saveJSONObj("PrimaryKeyColumn", json.toString());
Thanks Tichodroma,
But as i told i am using net.sf.json.JSONObject class and above things we can achieve from this class too..What i did to solve the above issue?...Please have a look on the Java code...
JSONObject jsonObj = new JSONObject();
JSONObject obj = jsonObj.fromObject(userReorderOption);
JSONArray columnName = (JSONArray) obj.get("COLUMN");
for (int i = 0; i < columnName.size(); i++) {
System.out.println(columnName.getString(i));
}
This code work fine for me with my Json Jar**(net.sf.json)**
Your JSON is not a JSONArray.
A JSONArray is an ordered sequence of values.
You have a JSONObject.
A JSONObject is an unordered collection of name/value pairs.
Edit:
Using the JSON implementation from org.codehaus.jettison.json, you can do this:
String json = "{\"COLUMN\":[\"Type\",\"Sub Type\",\"F.P.\",\"P.P.\",\"Process\",\"Due To Start\"]}";
JSONObject obj = new JSONObject(json);
JSONArray column = (JSONArray) obj.get("COLUMN");
for (int i = 0; i < column.length(); i++) {
final String field = column.getString(i);
System.out.println(field);
}
Result:
Type
Sub Type
F.P.
P.P.
Process
Due To Start
I have the following array returned to my JAVA Android application from PHP:
Array ( [0] => Array ( [referral_fullname] => Name 1 [referral_balance] => 500 ) [1] => Array ( [referral_fullname] => Name 2 [referral_balance] => 500 ) );
In Java they above array looks like this:
{"0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}};
For a simple JSONObject I'm using:
JSONTokener tokener = new JSONTokener(result.toString());
JSONObject finalResult = new JSONObject(tokener);
referral_fullname = finalResult.getString("referral_fullname");
but for an array of objects I don't know!
String str = your Json-> apply to.String();
JSONObject jObject = new JSONObject(str);
Map<String,String> map = new HashMap<String,String>();
Iterator iter = jObject.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = jObject .getString(key);
map.put(key,value);
}
Your Json Syntax is wrong , JSONArray should be like this :
["0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}];
and to parse a JsonArray that contains some JSONObject , try this :
//parse the result
JSONObject jsonResult = null;
JSONArray arrayResult = null;
ArrayList<YourObject> listObjects = null;
try {
arrayResult = new JSONArray(result);
if(arrayResult != null) {
listObjects = new ArrayList<YourObject>();
int lenght = arrayResult.length();
for(int i=0; i< lenght; i++) {
JSONObject obj = arrayResult.getJSONObject(i);
YourObject object = new YourObject(obj);
listObjects.add(object);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
And add a constructor in your Class YourObject to convert your Json to an instance :
public YourObject(JSONObject json) {
if (!json.isNull("referral_fullname"))
this.referral_fullname = json.optString("referral_fullname", null);
if (!json.isNull("referral_balance"))
this.referral_balance = json.optString("referral_balance", null);
}
You should use
JSONArray finalResult = new JSONArray(tokener);
if you can. You structure is now an object with two fields, 0 and 1, which contains another object. You have to get an array of object in place of this composite object if you want to iterate easily like
JSONObject jso;
for(int i = finalResult.lenght-1; i >=0; i--){
jso = finalResult.get(i);
// jso == {"referral_fullname":"Name 1","referral_balance":"500"}
[whatever]
}
Try this.............
final JSONArray result_array = json.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
JSONObject joObject = result_array.getJSONObject(i);
String jName = joObject.get("referral_fullname").toString();
String jbalance = joObject.get("referral_balance").toString();
}
First make an JSON object and see then in inner level what you have if you have array then fetch array.
You need to make JSON object first. For example, if resp is a String (for example coming as http response)
JSONObject jsonObject = new JSONObject(resp);
jsonObject may contains other JSON Objects or JSON array. How to convert the JSON depends on the response.
If arraykey is a array inside the JSON objects then we can get list of array by the following way.
JSONArray arr = jsonObject.getJSONArray("arraykey");
Check the length of arr, if it is greater than 0 then it contains JSON objects or JSON array depending the data.
There is a complete example with some explanation about JSON String to JSON array can be found at
http://www.hemelix.com/JSONHandling
I am using the package org.json package: I need help with getting the corect data from the json in java. this is the string I have in json:
{"GetLocationsResult":[{"ID":82,"Name":"Malmo","isCity":true,"isCounty":false,"isDisctrict":false,"ID_Parent":null,"ID_Map":35,"ZipCode":"7000"},{"ID":82,"Name":"Trelleborg","isCity":true,"isCounty":false,"isDisctrict":false,"ID_Parent":null,"ID_Map":35,"ZipCode":"7000"}]}
This is a listing and this is just a test, it will contain more than 2 items, so my questions is, I want to get the name of all locations, I want to populate a spinner with names in my android app.
How can I get the "Name":"Malmo" and so on....
???
The answer is simple....The JSON element starts with a { which is a JSON Object, and GetLocationsResults is a JSON Array of JSON Objects. In essence, I translated the JSON String to the following code...
JSONObject rootJson = new JSONObject(jsonString);
JSONArray jsonArray = rootJson.getJSONArray("GetLocationsResult");
//Let's assume we need names....
String[] names = null;
if (jsonArray != null) {
names = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
names[i] = json.getString("Name");
}
}
//Test
for (String name: names) {
System.out.println(name);
}