Search code examples
androidjsonapiretrofitpojo

Easy way to parse Key value pair json


I want to parse the json . I know retrofit and working on it, but don't know how to parse the below json as it is not in correct format.

Kindly help me in solving this. Number of Universities in the json is not static they will change .

{
    "transactionid": "7ec7d209589ce2abdb2e555c26776c85",
    "returncode": "200",
    "returnmsg": "success",
    "university": {
        "1": "Anna University",
        "3": "Technological University",
    }
}

Solution

  • You can use JsonDeserializer, import in you gradle file

    com.squareup.retrofit2:converter-gson:2.1.0

    and use class below

     public static class MyDeserializer implements JsonDeserializer<YourResponseModel> {
    
        @Override
        public YourResponseModel deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            YourResponseModel response = new YourResponseModel();
            JsonObject jsonObject = json.getAsJsonObject();
            JsonObject university = jsonObject.getAsJsonObject("university");
            ArrayList<String> universities = new ArrayList<>();
            try {
                JSONObject object = new JSONObject(university.toString());
                Iterator<String> iter = object.keys();
                while (iter.hasNext()) {
                    String key = iter.next();
                    try {
                        String value = object.getString(key);
                        universities.add(value);
                    } catch (JSONException e) {
                        Log.e(TAG, "deserialize: ",e );
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            response.university = universities;
            return response;
        }
    }
    

    Create new GsonBuilder for the JsonDeserializer

    Gson gson = new GsonBuilder()
                    .registerTypeAdapter(YourResponseModel.class, new MyDeserializer())
                    .create();
    

    and finally set it to the Retrofit Builder

     Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
    

    You can get more information from this blog