Retrofit возвращает обязательные парки значений, отсутствующие в $, когда у меня нет основного элемента в JSON - PullRequest
0 голосов
/ 22 апреля 2020

Резюме: я пытаюсь получить данные из национальных парков (API), и у них есть JSON, у которого нет имени основного элемента. И кажется, что модификация смотрит на имя переменной для автоматического поиска элемента. Он не возвращает ошибку «Парки обязательных значений отсутствуют в $». У меня нет парков, но я вообще не ищу элемент парков. Я искал через stackoverflow, чтобы увидеть, если у кого-то есть подобная проблема и не нашел, поэтому я отправляю этот вопрос здесь.

Подробно: Вот json из API ...

{"total":"498","data":[{"contacts":{"phoneNumbers":[{"phoneNumber":"9372257705","description":"","extension":"","type":"Voice"}],"emailAddresses":[{"description":"","emailAddress":"tom_engberg@nps.gov"}]},"states":"OH","longitude":"-84.0711364746094","activities":[{"id":"B33DC9B6-0B7D-4322-BAD7-A13A34C584A3","name":"Guided Tours"}],"entranceFees":[{"cost":"1.0000","description":"The National Aviation Heritage Area is comprised of many sites. While some sites are free of charge to the public, others may have entrance fees and\/or event or participation fees. Please check on the specific National Aviation Heritage Area site prior to your visit.","title":"Entrance Fees Vary"}],"directionsInfo":"The National Aviation Heritage Area has multiple sites located throughout eight counties in the Dayton, Ohio and western Ohio area. Please be sure to visit a specific National Aviation Heritage Area website for directions and\/or maps to each location.","entrancePasses":[{"cost":"1.0000","description":"The National Aviation Heritage Area is comprised of many sites. While some sites are free of charge to the public, others may have entrance fees and\/or event or participation fees. Please check on the specific National Aviation Heritage Area site prior to your visit.","title":"Fee Pass Costs Vary"}],"directionsUrl":"http:\/\/www.aviationheritagearea.org\/","url":"https:\/\/www.nps.gov\/avia\/index.htm","weatherInfo":"The National Aviation Heritage Area lies in a humid continental zone with a generally temperate climate. Winters are mildly cold with average temperatures around 39 degrees (F). Summers are hot and humid with an average temperature around 74 degrees (F). Average annual total rainfall is just above 41\". Snowfall in the winter is generally light with an average total snowfall of about 25\".","name":"National Aviation","operatingHours":[{"exceptions":[],"description":"While this website is not meant to be an exhaustive resource for all of the National Aviation Heritage Area partners and organizations, there is an official partner organization (National Aviation Heritage Alliance) which operates a separate and full-functioning website with a plethora of site information. Visit National Aviation Heritage Alliances' webpage for up-to-date information, directions and breaking news for all of the historical sites and member organizations.","standardHours":{"wednesday":"All Day","monday":"All Day","thursday":"All Day","sunday":"All Day","tuesday":"All Day","friday":"All Day","saturday":"All Day"},"name":"Various Heritage Area Sites"}],"topics":[{"id":"B912363F-771C-4098-BA3A-938DF38A9D7E","name":"Aviation"}],"latLong":"lat:39.9818229675293, long:-84.0711364746094","description":"Aviation is chock-full of tradition & history and nowhere will you find a richer collection of aviation than here, the birthplace of aviation.  From the straightforward bicycle shops that fostered the Wright brothers' flying ambitions to the complex spacecraft that carried man to the moon, the National Aviation Heritage Area has everything you need to learn about this country’s aviation legacy.","images":[{"credit":"NPS Photo \/ Tom Engberg","altText":"Visitor center building in background with plaza in foreground","title":"Dayton's National Park","caption":"The Wright-Dunbar Interpretive Center located just west of downtown Dayton","url":"https:\/\/www.nps.gov\/common\/uploads\/structured_data\/DCB2628F-1DD8-B71B-0BD78D1063069C70.jpg"}],"designation":"Heritage Area","parkCode":"avia","addresses":[{"postalCode":"45402","city":"Dayton","stateCode":"OH","line1":"16 South Williams St.","type":"Physical","line3":"","line2":""},{"postalCode":"45402","city":"Dayton","stateCode":"OH","line1":"16 South Williams St.","type":"Mailing","line3":"","line2":""}],"id":"C8C207D8-49C4-4891-9915-0007205A0284","fullName":"National Aviation Heritage Area","latitude":"39.9818229675293"}],"limit":"1","start":"1"}

Ниже приведен класс данных, который я написал:

data class NetworkParkContainer(val parks: List<NetworkPark>)
data class NetworkPark(
    val data: List<Data>,
    val limit: String,
    val start: String,
    val total: String
)

Вот код, который я вызвал для получения данных JSON:

interface ParksApiService {
    companion object {
        val API_KEY = "<my own api key value>"
    }
    @GET("parks")
    suspend fun getParks(@Query("api_key") type: String, @Query("limit") limit: Int): NetworkParkContainer
}

Зачем искать Retrofit 2 ' парки? Ни в одном из моих классов данных нет «парков». Кажется, он смотрит на «парки» в:

data class NetworkParkContainer(val parks: List<NetworkPark>)

Как бы я сказал дооснащению, что я хочу все это так, как я написал класс данных NetworkPark, который даже не включает «парки»?

Вот путь API: https://developer.nps.gov/api/v1/parks?api_key= & limit = 1

Мой базовый URL-адрес https://developer.nps.gov/api/v1/

Так что мой @GET - парки поэтому должно получиться так: https://developer.nps.gov/api/v1/parks?api_key= & limit = 1

1 Ответ

0 голосов
/ 22 апреля 2020

Ваш класс данных выполняет неправильное отображение. Вы должны убедиться, что ваши ключи от API имеют то же имя, что и класс данных, поскольку GSON использует эти значения, а не модификацию. Модифицированный просто выбирает данные и затем передает их GSON для десериализации. Если API возвращает странные имена и вы не хотите, чтобы это было в ваших классах данных, тогда используйте @ SerializedName ("newName: String") для параметра в классе данных.

SOLUTION

data class NetworkPark(
  val total: String,
  val data: List<Data>,
  val limit: String,
  val start: String
)

Этот класс данных является избыточным:

data class NetworkParkContainer(val parks: List<NetworkPark>)

Изменения в интерфейсе:

interface ParksApiService {
companion object {
    val API_KEY = "<my own api key value>"
}

@GET("parks")
suspend fun getParks(@Query("api_key") type: String, @Query("limit") limit: Int): NetworkPark
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...