Правильно сохранить json ответ - PullRequest
0 голосов
/ 23 апреля 2020

Я пытаюсь получить ответ json и сохранить его в моделях, но у меня возникли проблемы, вот код, который у меня есть сейчас

Call<Forum> call = apiInterface.getForums();
call.enqueue(new Callback<Forum>() {

    @Override
    public void onResponse(Call<Forum> call, Response<Forum> response) {
        if (!response.isSuccessful()) {
            //show error
        }

        Forum forum = response.body();

        //both of these return null
        System.out.println("id: " + forum.getId());
        System.out.println("theme: " + forum.getTheme());

    }

    @Override
    public void onFailure(Call<Forum> call, Throwable t) {
       //show error
    }
});

Это json Ответ: меня интересует только главный объект, все, что находится внутри группового объекта, мне не нужно сохранять, я хочу сохранить id, theme, description, anonymous, start_date, end_date только в тот момент, когда мне не нужно изображение или видео, но, возможно, в будущем я буду Я не уверен, как сохранить их в модели. любые предложения приветствуются

{
  "forums": [
    {
      "id": 1,
      "theme": "new forum",
      "description": "<p>adsadsfds asd adsa <strong>dfasdfa <\/strong>s fsda<\/p>",
      "user_id": 1,
      "anonymous": 0,
      "start_date": "2020-04-12 12:00:00",
      "end_date": "2020-04-30 12:00:00",
      "image": null,
      "video": null,
      "created_at": "2020-04-20 11:01:52",
      "updated_at": "2020-04-20 11:01:52",
      "group": [
        {
          "id": 1,
          "name": "Grupo 1",
          "user_id": 1,
          "course_id": 1,
          "major_id": 1,
          "period_id": 2,
          "classroom_id": 1,
          "created_at": null,
          "updated_at": null,
          "pivot": {
            "discussion_forum_id": 1,
            "group_id": 1
          },
          "users": [
            {
              "id": 1,
              "name": "sadmin",
              "lastname": "apellido",
              "maidenname": "apellido2",
              "card": "1111",
              "scard": "123",
              "user_type_id": 1,
              "email": "sadmin@gmail.com",
              "created_at": "2020-03-20 10:28:36",
              "updated_at": "2020-03-20 10:28:36",
              "pivot": {
                "group_id": 1,
                "user_id": 1
              }
            }
          ]
        },
        {
          "id": 2,
          "name": "Grupo 2",
          "user_id": 1,
          "course_id": 2,
          "major_id": 2,
          "period_id": 2,
          "classroom_id": 4,
          "created_at": null,
          "updated_at": null,
          "pivot": {
            "discussion_forum_id": 1,
            "group_id": 2
          },
          "users": [
            {
              "id": 2,
              "name": "admin",
              "lastname": "apellido",
              "maidenname": "apellido2",
              "card": "2222",
              "scard": "234",
              "user_type_id": 2,
              "email": "admin@gmail.com",
              "created_at": "2020-03-20 10:28:37",
              "updated_at": "2020-03-20 10:28:37",
              "pivot": {
                "group_id": 2,
                "user_id": 2
              }
            }
          ]
        }
      ]
    }
  ]
}

Это модель POJO для форумов

 @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("theme")
    @Expose
    private String theme;
    @SerializedName("description")
    @Expose
    private String description;
    @SerializedName("anonymous")
    @Expose
    private Integer anonymous;
    @SerializedName("start_date")
    @Expose
    private String startDate;
    @SerializedName("end_date")
    @Expose
    private String endDate;

    //Setters and Getters here

REtrofit2 client

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        Gson gson = new GsonBuilder().serializeNulls().setLenient().create();

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @NotNull
                    @Override
                    public okhttp3.Response intercept(@NotNull Chain chain) throws IOException {
                        Request originalRequest = chain.request();
                        Request newRequest = originalRequest.newBuilder()
                                .header("Authorization", "Bearer " + token)
                                .build();

                        return chain.proceed(newRequest);
                    }
                })
                .addInterceptor(interceptor)
                .build();

        retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.0.2:8000/api/")
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();

1 Ответ

1 голос
/ 23 апреля 2020

Похоже, ваш JSON ответ возвращает список. Пожалуйста, попробуйте, как показано ниже:

   Call<List<Forum>> call = apiInterface.getForums();
    call.enqueue(new Callback<List<Forum>>() {

        @Override
        public void onResponse(Call<List<Forum>> call, Response<List<Forum>> response) {
            if (!response.isSuccessful()) {
                //show error
            }

            List<Forum> forums = response.body();

            forums.forEach(forum -> {
                System.out.println("id: " + forum.getId());
                System.out.println("theme: " + forum.getTheme());
            });

        }

        @Override
        public void onFailure(Call<Forum> call, Throwable t) {
           //show error
        }
    });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...