How to grab JSON Array and use gson to parse each json object? (Retrofit)

后端 未结 4 1443
忘掉有多难
忘掉有多难 2020-12-30 23:05

I am returning an array of results with my json Objects, and I am trying to use my customObjectResponse class to pull out each of the fields within each of the objects... th

4条回答
  •  灰色年华
    2020-12-30 23:47

    I originally had trouble getting an idea of how the OP solved his problem but, after days of debugging I have finally figured out how to solve this issue.

    So you essentially have data in the format like so (JSON Array of JSON Objects):

    [
        {
          ...
        }
    ] 
    

    Your class that models the data and contains the getter and setter methods are nothing more than your typical POJO.

    public class Person implements Serializable {
        @SerializedName("Exact format of your json field name goes here")
        private String firstName;
    
        // Getters and Setters....
    }
    

    In your interface that contains your RESTful annotations you want to convert your call from:

    Before:

    public interface APInterface {
        @GET("SOME URL TO YOUR JSON ARRAY")
        Call(...)
    }
    

    After:

    public interface APInterface {
        @GET("SOME URL TO YOUR JSON ARRAY")
        Call>(...)
    }
    

    In your android activity you want to convert all calls in the form of Call to Call>

    Finally when making the initial asynchronous request call, you will want to convert your callbacks like so.

    call.enqueue(new Callback>() {
        @Override
        public void onResponse(Call> call, Response> response) {
    
            if(response.isSuccessful()){
                List person = response.body();
    
               // Can iterate through list and grab Getters from POJO
               for(Person p: person){...}
    
    
            } else {
                // Error response...
            }
    
        }
    
        @Override
        public void onFailure(Call> call, Throwable t) {...}
    });
    

    Hope this helps others whom are lost from the accepted answer above.

提交回复
热议问题