>

Retrofit 라이브러리를 공부하기 시작해서 약간의 도움을 요청하십시오. 응답에서 데이터를 가져 오려고하지만 객체에 대한 링크 만 얻습니다.

interface IApi {
@GET("api")
Call<PostModel> getData();
}
/*---------------------------------------------------------------------*/
public class App extends Application {
private static IApi siteApi;
@Override
public void onCreate() {
    super.onCreate();
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://yesno.wtf/")
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build();
    siteApi = retrofit.create(IApi.class);
}
public static IApi getApi() {
    return siteApi;
}
}
/*------------------------------------------------------------------------*/
class PostModel {
    @SerializedName("answer")
    @Expose
    private String answer;
    @SerializedName("forced")
    @Expose
    private Boolean forced;
    @SerializedName("image")
    @Expose
    private String image;
    public String getAnswer() {
        return answer;
    }
    public void setAnswer(String answer) {
        this.answer = answer;
    }
    public Boolean getForced() {
        return forced;
    }
    public void setForced(Boolean forced) {
        this.forced = forced;
    }
    public String getImage() {
        return image;
    }
    public void setImage(String image) {
        this.image = image;
    }
    }
/*------------------------------------------------------------------------*/
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    App.getApi().getData().enqueue(new Callback<PostModel>() {
        @Override
        public void onResponse(Call<PostModel> call, Response<PostModel> response) {
            Log.e("Response", response.body().toString());
        }
        @Override
        public void onFailure(Call<PostModel> call, Throwable t) {
            t.printStackTrace();
            Toast.makeText(MainActivity.this, "An error occurred during networking", Toast.LENGTH_SHORT).show();
        }
    });
}
}

변수 유형에 문제가있는 것 같지만 확실하지 않습니다 ... 어떤 도움을 주셔서 감사합니다.

UPD : 내 logcat :

...

D/OkHttp {"answer":"no","forced":false,"image":"https://yesno.wtf/assets/no/27-8befe9bcaeb66f865dd3ecdcf8821f51.gif"}

D/OkHttp: <-- END HTTP (108-byte body)

E/Response: com.testapp.retrofit.PostModel@9a74b2c

그래서 질문은 어떻게 대답 할 수 있는가? ( "answer": "no", "forced": false, "image": " https://yesno.wtf/assets/no/27-8befe9bcaeb66f865dd3ecdcf8821f51.gif ")


  • 답변 # 1

    응답에 따라

    모델 PostModel이 잘 보입니다. 당신의 방식으로 나의 실례를 시험해보십시오

    인터페이스

     public interface ServiceInterface {
            @GET(HttpConstants.USERDATAJSON)
            Call<ListData>taskData(@Query("method")String method,@Query("stdID")int stdID);
        }
    
    

    서비스 클래스

    public class ServiceClass {
            static ServiceInterface serviceInterface;
        //    public static final String baseUrl= HttpConstants.BASE_URL_GEONAME;
            public static final String baseUrl= HttpConstants.baseUrl;
            public static ServiceInterface connection(){
                if(serviceInterface==null){
                    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
                    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                    OkHttpClient client = new OkHttpClient();
                    client.interceptors().add(new Interceptor() {
                        @Override
                        public Response intercept(Chain chain) throws IOException {
                            Response response=chain.proceed(chain.request());
                            return response;
                        }
                    });
                    Retrofit retrofit = new Retrofit.Builder()
                            .client(client)
                            .addConverterFactory(GsonConverterFactory.create())
                            .baseUrl(baseUrl)
                            .build();
                    serviceInterface=retrofit.create(ServiceInterface.class);
                }
                return serviceInterface;
            }
        }
    
    

    전화

    public void getTaskData(){
            ServiceInterface serviceInterface=ServiceClass.connection();
            Call<ListData> call=serviceInterface.taskData("getAllUsersSimple",0);
            call.enqueue(new Callback<ListData>() {
                @Override
                public void onResponse(Response<ListData> response, Retrofit retrofit) {
                    Log.v("@@@Response",""+response.toString());
                    if(response.isSuccess()){
                        listData=response.body();
                        dataList=listData.getData();
                        printStudentDetails(dataList);
                    }
                }
                @Override
                public void onFailure(Throwable t) {
                    Log.v("@@@Failure"," Message"+t.getMessage());
                }
            });
        }
    
    

    모델

    public class ListData {
        @SerializedName("data")
        @Expose
        private List<DataPojo> data = null;
        @SerializedName("code")
        @Expose
        private Integer code;
        @SerializedName("message")
        @Expose
        private String message;
        public List<DataPojo> getData() {
            return data;
        }
        public void setData(List<DataPojo> data) {
            this.data = data;
        }
        public Integer getCode() {
            return code;
        }
        public void setCode(Integer code) {
            this.code = code;
        }
        public String getMessage() {
            return message;
        }
        public void setMessage(String message) {
            this.message = message;
        }
    }
    public class DataPojo {
        @SerializedName("user_id")
        @Expose
        private String userId;
        @SerializedName("user_name")
        @Expose
        private String userName;
        @SerializedName("user_age")
        @Expose
        private String userAge;
        public String getUserId() {
            return userId;
        }
        public void setUserId(String userId) {
            this.userId = userId;
        }
        public String getUserName() {
            return userName;
        }
        public void setUserName(String userName) {
            this.userName = userName;
        }
        public String getUserAge() {
            return userAge;
        }
        public void setUserAge(String userAge) {
            this.userAge = userAge;
        }
    }
    
    

    자세한 참조를 위해 방문하십시오 https://github.com/pratikvyas1991/NetworkingExample/tree/master/app/src/main/java/com/ims/tasol/networkingexample

관련 자료

  • 이전 reactjs - 반응 - 다른 페이지 세트에 대한 라우트 설정
  • 다음 php - 워드 프레스 - 메타 필드의 이름을 얻고 싶습니다