Retrofit 不会从 Kotlin 中的 API 返回数据

问题描述 投票:0回答:1

我正在 Android Studio (Kotlin) 中使用 Retrofit 从学校项目的 Open Food Facts API 获取数据。程序与 API 连接并成功返回代码和状态,但所有其他变量均返回为 0 或 null(取决于数据类型)。我在网上没有找到任何解决方案,也不知道问题出在哪里,因为与API的连接似乎没有任何问题,但变量数据没有返回。

链接到我正在测试的数据集:https://world.openfoodfacts.org/api/v2/product/737628064502.json

这是调用 @GET 函数的类:

package com.example.commandercalorie.ui.dashboard

import ApiClient
import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.commandercalorie.Food
import com.example.commandercalorie.MyAdapter
import com.example.commandercalorie.Post
import com.example.commandercalorie.databinding.FragmentDashboardBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class DashboardFragment : Fragment() {

// some other code

        searchButton.setOnClickListener {
            val codeId = 737628064502 // the variable for the barcode/id of the product

            val call = ApiClient.apiService.getPostById(codeId)

            call.enqueue(object : Callback<Post> {
                override fun onResponse(call: Call<Post>, response: Response<Post>) {
                    if (response.isSuccessful) {
                        val post = response.body()
                        val productName = post?.product_name

// some other code

                    } else {
                        // some other code
                    }
                }

                override fun onFailure(call: Call<Post>, t: Throwable) {
                    // Handle failure}

// some other code

这是 Retrofit 客户端和 API 客户端:

import com.example.commandercalorie.ApiService
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

object RetrofitClient {
    private const val BASE_URL = "https://world.openfoodfacts.org/api/v2/"

    val retrofit: Retrofit by lazy {
        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }
}

object ApiClient {
    val apiService: ApiService by lazy {
        RetrofitClient.retrofit.create(ApiService::class.java)
    }
}

这是API-Service接口:

package com.example.commandercalorie

import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Path

interface ApiService {
    @GET("product/{code}")
    fun getPostById(@Path("code") codeId: Long): Call<Post>
}

这是具有所需变量的数据类:

package com.example.commandercalorie


data class Post (
    val code: String,
    val origins: String,
    val energy_100g: Int,
    val product_name: String,
    val status: Int
)

Logcat 中 API 的输出:

output API

变量origins、energy_100g和product_name的输出不应该是0和null,因为这些变量在数据集中有一个分配的值。 Android Studio 没有显示任何错误消息,并且状态 + 代码正确返回。

我将非常感谢有关此问题的任何帮助。

kotlin retrofit retrofit2
1个回答
0
投票

也许这会有所帮助,我不是 Android 开发方面最有经验的人。这是一个嵌套的 JSON,也许您需要访问嵌套字段。

更新模型的数据类以实现类似的功能。

data class Post (
    val code: String,
    val product: Product,      
    val status: Int
)

data class Product (
    val origins: String,
    @SerializedName("product_name")
    val productName: String,
    val nutriments: Nutriments,
)

data class Nutriments (
    @SerializedName("energy_100g")
    val energy100g: Int,

祝你好运,伙计。

© www.soinside.com 2019 - 2024. All rights reserved.