Android get specific data from JSON - java
I'm newbie on android and I'm trying to create an application that catch data from JSON.
For now I already get all data, but the problem is how can I get specific data that I only need.
Here's my JSON example
[{"id":"152","category_id":"1","item_name":"Restaurant1","description":"Restaurant1","address":"Restaurant1","area":"42","area_name":"Kuta","longitude":"2131","latitude":"1231","open_detail":"24hours","kids":"","free_text_for_kids":"","cuisine_id":"3","cuisine_name":"Chinese","cuisine_uniqe_code":"CNS","price_category":"5","hotel_official_star_rating":"0","phone":"123","mobile_phone":"123","review":"Restaurant1","promotion":"0","promotion_free_text":"","promotion_start_date":"0000-00-00","promotion_end_date":"0000-00-00","active":"1","image_count":"3","created_date":"1401644001","created_by":"1","updated_date":"1402029631","updated_by":"1","facebook":"Restaurant1","twitter":"Restaurant1","instagram":"Restaurant1"},
{"id":"153","category_id":"1","item_name":"Restaurant2","description":"Restaurant2","address":"Restaurant2","area":"42","area_name":"Kuta","longitude":"1231","latitude":"1231231","open_detail":"24hours","kids":"","free_text_for_kids":"","cuisine_id":"17","cuisine_name":"Middle Eastern","cuisine_uniqe_code":"MID","price_category":"3","hotel_official_star_rating":"0","phone":"1231","mobile_phone":"231","review":"Restaurant2","promotion":"0","promotion_free_text":"","promotion_start_date":"0000-00-00","promotion_end_date":"0000-00-00","active":"1","image_count":"0","created_date":"1401644082","created_by":"1","updated_date":"1402029930","updated_by":"1","facebook":"Restaurant2","twitter":"Restaurant2","instagram":"Restaurant2"},
{"id":"162","category_id":"2","item_name":"Bars1","description":"Bars1","address":"Bars1","area":"34","area_name":"Seminyak","longitude":"213312","latitude":"21312","open_detail":"Bars1","kids":"","free_text_for_kids":"","cuisine_id":"","cuisine_name":null,"cuisine_uniqe_code":null,"price_category":"2","hotel_official_star_rating":"0","phone":"1231","mobile_phone":"1231","review":"Bars1","promotion":"0","promotion_free_text":"","promotion_start_date":"0000-00-00","promotion_end_date":"0000-00-00","active":"1","image_count":"0","created_date":"1401644461","created_by":"1","updated_date":"1402939937","updated_by":"1","facebook":"Bars1","twitter":"Bars1","instagram":"Bars1"},
{"id":"163","category_id":"2","item_name":"Bars2","description":"Bars2","address":"Bars2","area":"42","area_name":"Kuta","longitude":"1232131","latitude":"231","open_detail":"Bars2","kids":"","free_text_for_kids":"","cuisine_id":"","cuisine_name":null,"cuisine_uniqe_code":null,"price_category":"5","hotel_official_star_rating":"0","phone":"11231","mobile_phone":"213","review":"Bars2","promotion":"0","promotion_free_text":"","promotion_start_date":"0000-00-00","promotion_end_date":"0000-00-00","active":"1","image_count":"0","created_date":"1401644494","created_by":"1","updated_date":"1402030999","updated_by":"1","facebook":"Bars2","twitter":"Bars2","instagram":"Bars2"},
As you can see, there's two type category_id, how can I get only category_id "1" for restaurant.
I know that I have to use if statement, but where should I put it?
Here's My java code
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
restaurant = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < restaurant.length(); i++) {
JSONObject c = restaurant.getJSONObject(i);
String item_name = c.getString(TAG_ITEM_NAME);
String cuisine_name = c.getString(TAG_CUISINE_NAME);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ITEM_NAME, item_name);
contact.put(TAG_CUISINE_NAME, cuisine_name);
// adding contact to contact list
restaurantList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
Thanks Before :D
Create an if statement that checks if the category is 1 and if it is then add the to the HashMap if it is not then do not do anything continue to the next json object.
sample:
for (int i = 0; i < restaurant.length(); i++) {
JSONObject c = restaurant.getJSONObject(i);
String category = c.getString("category_id");
if(category.equals("1"))
{
String item_name = c.getString(TAG_ITEM_NAME);
String cuisine_name = c.getString(TAG_CUISINE_NAME);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ITEM_NAME, item_name);
contact.put(TAG_CUISINE_NAME, cuisine_name);
// adding contact to contact list
restaurantList.add(contact);
}
}
Actually I found the answer by myself.
Here's the code that I use
for (int i = 0; i < restaurant.length(); i++) {
JSONObject c = restaurant.getJSONObject(i);
if(c.getString("category_id").equals("1")) {
String item_name = c.getString(TAG_ITEM_NAME);
String cuisine_name = c.getString(TAG_CUISINE_NAME);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ITEM_NAME, item_name);
contact.put(TAG_CUISINE_NAME, cuisine_name);
// adding contact to contact list
restaurantList.add(contact);
}
}
Thanks a lot for everyone that already answer it. I really appriciate it :D
Related
How to add two maps to the List
Code is: How can to add the Map to the List public List<Map<Object, Object>> getReportees(String idOfEmp) throws Exception { JSONArray jsonarr_s = (JSONArray) jobj.get("list"); Map<Object, Object> map = new HashMap<Object, Object>(); if (jsonarr_s.size() > 0) { // Get data for List array for (int i = 0; i < jsonarr_s.size(); i++) { JSONObject jsonobj_1 = (JSONObject) jsonarr_s.get(i); JSONObject jive = (JSONObject) jsonobj_1.get("jive"); Object names = jsonobj_1.get("displayName"); Object userid = jive.get("username"); map.put(names, userid); //return the map with the key value pairs map = new HashMap<Object, Object>(); String UserId = userid.toString(); String output1 = resp1.getEntity(String.class); JSONObject jobjs = (JSONObject) new JSONParser().parse(output1); // Store the JSON object in JSON array as objects (For level 1 array element i.e // issues) JSONArray jsonarr_new = (JSONArray) jobjs.get("issues"); int numofjiras = jsonarr_new.size(); //this jira count must be mapped to the name and id map.put("count", numofjiras); } return map; } else { map.put("errorcheck", msg); } return map; } } I want the output like: Name id count AJ 235457 2 Geet 637571 0 Actually I am getting the Name and id in key value pairs.Then I am trying to pass each id to an api which will give me the count.So how can I return all the fileds i.e Name ,id and count.So here I am trying to map like for this Userid and Name this is the count.How can we acheive it.Plesae help.Thanks in advnce.
I think you can try creating a new class to represent each row in your output. For example, you can create an Employee class like this: public class Employee { private long id; private String name; private int issueCount; //getters and setters } You can, then, use this class and assign the values from the JSONArray arrays to it. Once you get the value for "count", you can just add the Employee object to the map (or list). Hope this helps.
You would need to declare a local list first and then return that list: public List<Map<Object, Object>> getReportees(String idOfEmp) throws Exception { JSONArray jsonarr_s = (JSONArray) jobj.get("list"); Map<Object, Object> map = new HashMap<Object, Object>(); List<Map<Object, Object>> resultList = new ArrayList<Map<Object,Object>>(); if (jsonarr_s.size() > 0) { // Get data for List array for (int i = 0; i < jsonarr_s.size(); i++) { JSONObject jsonobj_1 = (JSONObject) jsonarr_s.get(i); JSONObject jive = (JSONObject) jsonobj_1.get("jive"); Object names = jsonobj_1.get("displayName"); Object userid = jive.get("username"); map.put(names, userid); //return the map with the key value pairs String UserId = userid.toString(); String output1 = resp1.getEntity(String.class); JSONObject jobjs = (JSONObject) new JSONParser().parse(output1); // Store the JSON object in JSON array as objects (For level 1 array element i.e // issues) JSONArray jsonarr_new = (JSONArray) jobjs.get("issues"); int numofjiras = jsonarr_new.size(); //this jira count must be mapped to the name and id map.put("count", numofjiras); } resultList.add(map); } else { map.put("errorcheck", msg); resultList.add(map); } return resultList; } Based on your results though you should consider flipping your data objects to instead be Map<Object, List<Object>> where the first Object in the map which is they key the name and then the list would contain two objects [id, count].
How to get key from json object
I have the json array : {"objets":{"1":"Question","2":"Response"},"success":true} I want to test if the text selected on spinner exist in the array it will return the number (1 or 2). Here is what I've done until now : String responseContent = response.asString(); Log.d("OBJECTS", responseContent); try { JSONObject jobj = new JSONObject(responseContent); JSONObject users = jobj.getJSONObject("objetcs"); Log.e("hello", String.valueOf(users)); if(users.toString().contains(spinner_objet.getSelectedItem().toString().trim())){ Log.e("hello", "it exist"); String user=users.getString("id"); Log.e("hello1", String.valueOf(user)); } } catch (JSONException e1) { e1.printStackTrace(); } But I'm not getting any thing, can any one help me with this ?
You can parse your Json into a hashMap like so : JSONObject object = new JSONObject(); Map<String,Integer> map = new HashMap<>(); while (object.keys().hasNext() ){ Integer key = (Integer) object.keys().next(); map.put((String) object.get(String.valueOf(key)), key); } You can then use the values of the map to put in the spinner. map.values(); Whenever the user selects from the spinner, you can get the id from the map.
JSONObject parse dictionary objects
JSON values that I get from server: { "Status":0, "Message":"", "Result":{"0B":"S.C. Blue Air","0Y":"FlyYeti","1X":"Branson Air"} } Getting the result as 'response' after connection and I am able to show my JSON string results on the screen. JSONObject json = new JSONObject(response); String status = json.getString("Status"); String message = json.getString("Message"); String result = json.getString("Result"); responseView.setText("Status" + status+ "Message" + message" + Result" + result); I am okay the results of "Status" and "Message" but not with "Result" because want to separate "Result" objects as and able use each of them as objects. For example: When I type OB in my app, I will get the result S.C. Blue Air
Instead of : String result = json.getString("Result"); use if(json.get("Result") instanceof JSONObject){ JSONObject object = (JSONObject) json.get("Result"); //do what you want with JSONObject String ob = object.get("0B"); } If you want to store it some way you can put it to Map or create object if always it is same data
You can use some libraries such as Gson (Google) or Moshi (Square) Those libraries allows you to declare your model as a plain java class (commonly called POJOS) annotated in some way that this libraries bind your properties in the JSON to your java properties. In your case: JSON: { "Status":0, "Message":"", "Result":{"0B":"S.C. Blue Air","0Y":"FlyYeti","1X":"Branson Air"} } MODEL: public class MyCallResponse { #SerializedName("Status") int status; #SerializedName("Message") String message; #SerializedName("Result") Result result; } public class Result { #SerializedName("0B") String b; #SerializedName("0Y") String y; #SerializedName("0X") String x; } In this case, with Gson you can do: MyCallResponse response = new Gson().fromJson(json, MyCallResponse.class); Log.i("Response b", response.result.b); Look at the documentation for more information about both libraries.
try this : JSONObject json = new JSONObject(response); JSONObject resultObj = json.getJSONObject("Result"); String OB = resultObj.getString("OB");
Try this String base = ""; //Your json string; JSONObject json = new JSONObject(base); JSONOBject resultJson = json.getJSONObject("Result"); // Get all json keys "OB", "OY", "1X" etc in Result, so that we can get values against each key. Set<Map.Entry<String, JsonElement>> entrySet = resultJson.entrySet(); Iterator iterator = entrySet.iterator(); for (int j = 0; j < entrySet.size(); j++) { String key = null; //key = "OB", "OY", "1X" etc try { Map.Entry entry = (Map.Entry) iterator.next (); key = entry.getKey ().toString (); //key = "OB", "OY", "1X" etc } catch (NoSuchElementException e) { e.printStackTrace (); } if (!TextUtils.isEmpty (key)) { Log.d ("JSON_KEY", key); String value = resultJson.getString(key); //for key = "0B", value = "S.C. Blue Air" //for key = "0Y", value = "FlyYeti" //for key = "1X", value = "Branson Air" } } It works with any array with dynamic json key. Don't forget to accept the answer & upvote if it works.
JSON Parsing in Java Webservice of multiple JSONObjects in JSONObject
This is my JSON string, { "listmain":{ "16":[{"brandid":"186"},{"brandid":"146"},{"brandid":"15"}], "17":[{"brandid":"1"}], "18":[{"brandid":"12"},{"brandid":"186"}], } } I need to get values in "16","17","18" tag and add values and ids("16","17","18") to two ArrayList. What i meant is, when we take "16", the following process should happen, List<String> lsubid = new ArrayList<String>(); List<String> lbrandid = new ArrayList<String>(); for(int i=0;i<number of elements in "16";i++) { lsubid.add("16"); lbrandid.add("ith value in tag "16" "); } finally the values in lsubid will be---> [16,16,16] the values in lbrandid will be---> [186,146,15] Can anyone please help me to complete this.
Use JSONObject keys() to get the key and then iterate each key to get to the dynamic value. You can parse the JSON like this JSONObject responseDataObj = new JSONObject(responseData); JSONObject listMainObj = responseDataObj.getJSONObject("listmain"); Iterator keys = listMainObj.keys(); while(keys.hasNext()) { // loop to get the dynamic key String currentDynamicKey = (String)keys.next(); //store key in an arraylist which is 16,17,... // get the value of the dynamic key JSONArray currentDynamicValue = listMainObj.getJSONArray(currentDynamicKey); int jsonrraySize = currentDynamicValue.length(); if(jsonrraySize > 0) { for (int i = 0; i < jsonrraySize; i++) { JSONObject brandidObj = currentDynamicValue.getJSONObject(i); String brandid = brandidObj.getString("brandid"); System.out.print("Brandid = " + brandid); //store brandid in an arraylist } } } Source of this answer
Use HashMap in XMLRPC result
I am new in Android development, and I am trying to receive a HashMap in RESULT by using XMLRPC but every time it's crash the application, this is my code please advice me : Object RESULT = XMLRPCClient.callEx(methodname,new Object[] {params}); Map FRESULT= (Map) RESULT;
I have been dealing with this also and managed to get the values this way: try { Object[] answer = (Object[]) client.call("call", sessionId, method, params); HashMap map = (HashMap) answer[0]; // get first item of the response because in my case the response was an array of Objects with one item in it holding the HashMap Object[] records = (Object[]) map.get("records"); // I only needed values from "records" key for (int i = 0; i < records.length; i++) { HashMap record = (HashMap) records[i]; // create another map from the records values, in my case uid's of categories Category cat = new Category(); // creating new instance of my Category class cat.setCatUid((String) record.get("uid")); // calling a method of the Category class to set Uid to the value from record HashMap m_categories.add(cat); // this adds it to my ArrayList<Category> } } catch (XMLRPCException e) { Log.e(method, "Exception", e); } I'm sure it's a mess, I'm noob in Java myself, but it worked for me. Hope it helps :)
Now the Application pass this peacefully after implementing : Object RESULT = XmlRpcConnect.ServerCall_a(method,new Object[] {params}); Map<String, Object> FRESULT= (HashMap<String, Object>) RESULT; with some changes in my XmlRpcConnect Class: #SuppressWarnings("unchecked"); public static Object ServerCall_a(String method, Object[] params){ XMLRPCClient client = new XMLRPCClient(server); HashMap<String, Object> result=null; try{ result = (HashMap<String, Object>) client.callEx(method, params); } catch(XMLRPCFault f){ // result = ("Fault message: " + f.getMessage()); } catch(XMLRPCException e){ // result = ("Exception message: " + e.getMessage()); } return result; } but when trying to extract the values it's crash again , any advice : if (FRESULT.get("status") == null) { result = (String) FRESULT.get("status"); toastDialog(result); }