how to use gson 2.0 on - onResponse from Retrofit 2.0

前端 未结 1 660
遇见更好的自我
遇见更好的自我 2020-12-22 12:39

i\'m doing an http call using the new retrofit 2.0, and getting a callback, i want to use gson 2.0 library to parse that json obj and to be able to do

json         


        
相关标签:
1条回答
  • 2020-12-22 13:26

    Okey i will explain how to convert JSON response to POJO :

    First of all you must create a POJO class in : JSON Schema 2 POJO

    1. Paste your example JSON response
    2. Select Source Type : JSON
    3. annotation style : Gson

    It will generate a POJO class for you.

    Then in your onResponse method :

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if(response.code()==200){
                Gson gson = new GsonBuilder().create();
                    YourPOJOClass yourpojo=new YourPOJOClass ();
                    try {
                        yourpojo= gson.fromJson(response.body().toString(),YourPOJOClass.class); 
                    } catch (IOException e) {
                        // handle failure to read error
                        Log.v("gson error","error when gson process");  
                    }
            }
    

    Dont forget to add compile 'com.google.code.gson:gson:2.4'

    Another way to do this : create a pojo class like in above.

    In your API :

    @POST("endpoint")
    public Call<YourPOJOClass> exampleRequest();
    

    When calling this :

        OkHttpClient okClient = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).build();
    
        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
                .create();
    
        Retrofit client = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .client(okClient)
                .build();
    
        YourApiClass service = client.create(YourApiClass.class);
    
        Call<YourPOJOClass> call=service.exampleRequest();
        call.enqueue(new Callback<YourPOJOClass>() {
            @Override
            public void onResponse(Call<YourPOJOClass> call, Response<YourPOJOClass> response) {
                //already Gson convertor factory converted your response body to pojo
                response.body().getCurserLocation();
            }
    
            @Override
            public void onFailure(Call<YourPOJOClass> call, Throwable t) {
    
            }
        });
    
    0 讨论(0)
提交回复
热议问题