Использование Zomato Api с модификацией

Я пытаюсь получить список ресторанов из Zomato Api с помощью RetroFit, но получаю только нулевые ответы и не могу найти, что я сделал неправильно. Я уже пытался изменить @Header на @Query и изменить тип ответа с ApiResponse на List<Restaurant>, но проблема сохраняется.

Это пример ответа на вызов конечной точки /search ZomatoApi.

"results_found": 4072,
  "results_start": 0,
  "results_shown": 1,
  "restaurants": [
    {
      "restaurant": {
        "R": {
          "has_menu_status": {
            "delivery": -1,
            "takeaway": -1
          },
          "res_id": 17836294,
          "is_grocery_store": false
        },
        "apikey": "75be9f9e2239fe637bf9cb1b46979d91",
        "id": "17836294",
        "name": "Cervejaria Meia Banana",
        "url": "https://www.zomato.com/porto/cervejaria-meia-banana-coimbrões?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "location": {
          "address": "Avenida do Infante Dom Henrique, 178, Coimbrões, Vila Nova de Gaia",
          "locality": "Coimbrões",
          "city": "Porto",
          "city_id": 311,
          "latitude": "41.1213507499",
          "longitude": "-8.6152520031",
          "zipcode": "",
          "country_id": 164,
          "locality_verbose": "Coimbrões, Porto"
        },
        "switch_to_order_menu": 0,
        "cuisines": "Portuguese, Finger Food, Petiscos",
        "timings": "08:00 to 24:00 (Mon, Tue, Wed, Thu, Sun), 08:00 to 02:00 (Fri-Sat)",
        "average_cost_for_two": 35,
        "price_range": 3,
        "currency": "€",
        "highlights": [
          "Lunch",
          "Debit Card",
          "Breakfast",
          "Dinner",
          "Indoor Seating",
          "Wine",
          "Fullbar",
          "Beer"
        ],
        "offers": [],
        "opentable_support": 0,
        "is_zomato_book_res": 0,
        "mezzo_provider": "OTHER",
        "is_book_form_web_view": 0,
        "book_form_web_view_url": "",
        "book_again_url": "",
        "thumb": "https://b.zmtcdn.com/data/res_imagery/17836294_RESTAURANT_2d9d944dfca0415414fdfeca7522c396.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A",
        "user_rating": {
          "aggregate_rating": "3.4",
          "rating_text": "Average",
          "rating_color": "CDD614",
          "rating_obj": {
            "title": {
              "text": "3.4"
            },
            "bg_color": {
              "type": "lime",
              "tint": "500"
            }
          },
          "votes": 24
        },
        "all_reviews_count": 10,
        "photos_url": "https://www.zomato.com/porto/cervejaria-meia-banana-coimbrões/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
        "photo_count": 30,
        "menu_url": "https://www.zomato.com/porto/cervejaria-meia-banana-coimbrões/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
        "featured_image": "https://b.zmtcdn.com/data/res_imagery/17836294_RESTAURANT_2d9d944dfca0415414fdfeca7522c396.jpg",
        "has_online_delivery": 0,
        "is_delivering_now": 0,
        "store_type": "",
        "include_bogo_offers": true,
        "deeplink": "zomato://restaurant/17836294",
        "is_table_reservation_supported": 0,
        "has_table_booking": 0,
        "events_url": "https://www.zomato.com/porto/cervejaria-meia-banana-coimbrões/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
        "phone_numbers": "22 3792953",
        "all_reviews": {
          "reviews": [
            {
              "review": []
            },
            {
              "review": []
            },
            {
              "review": []
            },
            {
              "review": []
            },
            {
              "review": []
            }
          ]
        },
        "establishment": [
          "Casual Dining"
        ],
        "establishment_types": []
      }
    }
  ]
}

API-интерфейс

public interface ZomatoApi {
    @GET("search")
    Call<ApiResponse> getNearbyRestaurants(@Query("lat") double lat, @Query("lon") double lon,
                        @Query("count") int count,@Query("radius") double radius, @Header("api_key") String apiKey);
}

Класс Апиответ

package com.cmuteam.app;

import java.util.List;

public class ApiResponse {
        private String results_found;
        private String  results_start;
        private String results_shown;
        private List<Restaurant> restaurants;

    public ApiResponse(String results_found, String results_start, String results_shown, List<Restaurant> restaurants) {
        this.results_found = results_found;
        this.results_start = results_start;
        this.results_shown = results_shown;
        this.restaurants = restaurants;
    }

    public String getResults_found() {
        return results_found;
    }

    public String getResults_start() {
        return results_start;
    }

    public String getResults_shown() {
        return results_shown;
    }

    public List<Restaurant> getRestaurants() {
        return restaurants;
    }
}

Класс ресторана

package com.cmuteam.app;

public class Restaurant {
    private String id;
    private String name;
    Location location;

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public Location getLocation() {
        return location;
    }

    public Restaurant(String id, String name, Location location) {
        this.id = id;
        this.name = name;
        this.location = location;
    }
}

Класс местоположения

public class Location {
    private String address;
    private String latitude;
    private String longitude;

    public Location(String address, String latitude, String longitude) {
        this.address = address;
        this.latitude = latitude;
        this.longitude = longitude;
    }

    public String getAddress() {
        return address;
    }

    public String getLatitude() {
        return latitude;
    }

    public String getLongitude() {
        return longitude;
    }

Фрагмент, где я делаю вызов API

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getContext();
        mAuth = FirebaseAuth.getInstance();
        restaurantsList= new ArrayList<>(50);
        getApi().getNearbyRestaurants(41.12108,-8.615718100000002,20,10000,"75be9f9e2239fe637bf9cb1b46979d91")
                .enqueue(new Callback<ApiResponse>() {
                    @Override
                    public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
                        List<Restaurant> restaurants=response.body().getRestaurants();
                        mAdapter = new RestaurantAdapter(context, restaurantsList);
                        RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(context, DividerItemDecoration.VERTICAL);
                        mRecyclerView.addItemDecoration(itemDecoration);
                        for (int i = 0; i < restaurants.size(); i++) {
                            restaurantsList.add(new Restaurant(restaurants.get(i).getId(),restaurants.get(i).getName(),restaurants.get(i).getLocation()));
                            mAdapter.notifyItemInserted(i);
                        }
                    }

                    @Override
                    public void onFailure(Call<ApiResponse> call, Throwable t) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                        builder.setMessage("Couldn´t find any nearby restaurants");
                        AlertDialog mDialog = builder.create();
                        mDialog.show();
                    }
                });
    }

@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View mContentView = inflater.inflate(R.layout.poi_list, container,false);
        mRecyclerView = mContentView.findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContentView.getContext()));
        mRecyclerView.setAdapter(mAdapter);
        return mContentView;
    }

    private Retrofit getRetrofit(){
        return new Retrofit.Builder()
                .baseUrl("https://developers.zomato.com/api/v2.1/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    private ZomatoApi getApi(){
        return  getRetrofit().create(ZomatoApi.class);
    }

person Community    schedule 28.08.2020    source источник


Ответы (1)


Заголовок авторизации называется user-key, а не api_key, как указано в документации zomato.

person Mohamed Hesham    schedule 28.08.2020
comment
он работал, но теперь говорит, что у меня нет подключенного адаптера - person ; 29.08.2020
comment
в дополнение к проблеме с заголовком вы столкнетесь с другой проблемой; класс ресторана не отображает объект ресторана, возвращаемый из ответа json. - person Mohamed Hesham; 29.08.2020
comment
почему не отображается? - person ; 29.08.2020
comment
вы должны установить адаптер на свой recyclerview recyclerview.setAdapter(adapter) - person Mohamed Hesham; 29.08.2020
comment
Это совершенно два разных объекта - person Mohamed Hesham; 29.08.2020
comment
Я установил его в методе onCreateView - person ; 29.08.2020
comment
Мохамед Хешам Мне нужен только идентификатор, имя и местоположение, нужно ли мне указывать их все как атрибуты в моем классе? - person ; 29.08.2020
comment
Адаптер настроен на просмотр ресайклера до того, как он уже инициализирован, адаптер инициализируется после возврата ответа из API, поэтому в onCreateView для него будет установлено значение null - person Mohamed Hesham; 29.08.2020
comment
Что касается сопоставления объектов, вы можете использовать этот веб-сайт jsonschema2pojo.org, чтобы убедиться, что ваше сопоставление правильное... он сгенерирует для вас файлы pojo. - person Mohamed Hesham; 29.08.2020
comment
Итак, я должен изменить свой setAdapter на ответ? - person ; 29.08.2020
comment
определенно ... вы должны установить его после получения ответа. - person Mohamed Hesham; 29.08.2020
comment
Я не уверен, как работает сайт. Должен ли я поместить свой ответ слева, а в типе источника выбрать схему JSON? - person ; 29.08.2020
comment
да, но установите счетчик на 1 ресторан только для того, чтобы веб-сайт мог анализировать ответ json - person Mohamed Hesham; 29.08.2020
comment
Спасибо, вы действительно помогли - person ; 29.08.2020