Prakash Kansurkar Prakash Kansurkar - 1 month ago 7
JSON Question

parse JSON response in android with multiple values

I am getting JSON response as the following string from a web page , I need to parse that response and store in Java array in android.

{"companyName":["Sanmar Group","Dcygnus Technocracy"]}{"CampusDate":["25/10/2016","24/10/2016"]}{"companyPackage":["3.67","1.8"]}{"status":["your are not eligible","your are not eligible"]}

How to achieve this.Thanks in advance.

Answer

Here is correct json format with parser {"companyName":["Sanmar Group","Dcygnus Technocracy"],"CampusDate":["25/10/2016","24/10/2016"],"companyPackage":["3.67","1.8"],"status":["your are not eligible","your are not eligible"]}

//Class to hold all value of a company

class CompanyInfo {
    public String companyName;
    public String CampusDate;
    public String companyPackage;
    public String status;
}

//Json Parser
class CompanyParser {

    public ArrayList<CompanyInfo> allComInfo;

    public CompanyParser() {
        allComInfo = new ArrayList<CompanyInfo>();
    }

    public void parseJson(String jsonString) {
        try {
            JSONObject reader = new JSONObject(jsonString);
            parseCompanyName(reader.getJSONArray("companyName"));
            parseCampusDate(reader.getJSONArray("CampusDate"));
            parseCompanyPackage(reader.getJSONArray("companyPackage"));
            parseStatus(reader.getJSONArray("status"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private void checkAndAddNewEmptyCompnayAtIndex(int index) {
        if (index >= allComInfo.size()) {
            allComInfo.add(new CompanyInfo());
        }
        else if(allComInfo.get(index) == null){
            allComInfo.add(new CompanyInfo());
        }
    }

    private void parseCompanyName(JSONArray data) throws JSONException {
        int size = data.length();
        for (int ak = 0; ak < size; ak++) {
            checkAndAddNewEmptyCompnayAtIndex(ak);
            allComInfo.get(ak).companyName = data.getString(ak);
        }
    }

    private void parseCampusDate(JSONArray data) throws JSONException {
        int size = data.length();
        for (int ak = 0; ak < size; ak++) {
            checkAndAddNewEmptyCompnayAtIndex(ak);
            allComInfo.get(ak).CampusDate = data.getString(ak);
        }
    }

    private void parseCompanyPackage(JSONArray data) throws JSONException {
        int size = data.length();
        for (int ak = 0; ak < size; ak++) {
            checkAndAddNewEmptyCompnayAtIndex(ak);
            allComInfo.get(ak).companyPackage = data.getString(ak);
        }
    }

    private void parseStatus(JSONArray data) throws JSONException {
        int size = data.length();
        for (int ak = 0; ak < size; ak++) {
            checkAndAddNewEmptyCompnayAtIndex(ak);
            allComInfo.get(ak).status = data.getString(ak);
        }
    }


}
Comments