How to filter data from Json in android?

前端 未结 3 1593
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-14 15:29

i am getting the data in json form like

{\"Users\":[
{\"category_id\":\"1\",\"user_email\":\"a@a.com\"},
{\"category_id\":\"5\",\"user_ema         


        
3条回答
  •  梦毁少年i
    2021-01-14 16:02

    First you need to create your variables in your activity

    //URL to get JSON
    private static String url = "your url to parse data";
    
    //JSON Node Names
    private static final String TAG_USERS = "users";
    private static final String TAG_CATEGORY_ID = "category_id";
    private static final String TAG_USER_EMAIL = "user_email";
    
    // Data JSONArray
    JSONArray users = null;
    
    //HashMap to keep your data
    ArrayList> userList;
    

    inside onCreate() function instantiate your userList

    userList = new ArrayList>();
    

    then you need to parse your data and populate this ArrayList in doInBackground() function

    //Create service handler class instance
    ServiceHandler sh = new ServiceHandler();
    
    //Url request and response
    String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
    Log.d("Response: ", "> " + jsonStr);
    
    if(jsonStr != null) {
        try {
            JSONObject jsonObj = new JSONObject(jsonStr);
    
            //Get Json Array Node
            users = jsonObj.getJSONArray(TAG_USERS);
    
            // Looping through all data
            for(int i = 0; i < users.length(); i++) {
                JSONObject u = users.getJSONObject(i);
    
                String category_id = u.getString(TAG_CATEGORY_ID);
                String user_email = u.getString(TAG_USER_EMAIL);
    
                // Temporary HashMap for single data
                HashMap user = new HashMap();
    
                // Adding each child node to Hashmap key -> value
                user.put(TAG_CATEGORY_ID, category_id);
                user.put(TAG_USER_EMAIL, user_email);
    
                //Adding user to userList
                userList.add(user);
            }
        }catch (JSONException e) {
            e.printStackTrace();
        }
    } else {
        Log.e("ServiceHandler", "Couldn't get any data from url");
    }
    

    Now you have your data stored in your userList. You can use your userList however you want. To get the category_id field in the list you can use this syntax

    // i being the counter of your loop
    String catId = userList.get(i).get("category_id");
    if(catId == 3) {
        ... your code
    }
    

提交回复
热议问题