API调用期望数组,获取一个对象

时间:2019-04-17 17:56:29

标签: android android-recyclerview retrofit2 recycler-adapter

我有一个API调用,该调用基本上在同一位置查找数组和对象。我正在尝试调用API并收到以下错误。 io.reactivex.exceptions.OnErrorNotImplementedException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

如何在属性类中同时调用根项和子项?

我在应用程序中进行了一些登录,URL正确,但是响应是问题

这是API-

{
    "id": "65",
    "name": "Switch - Kitchen",
    "label": "Switch - Kitchen",
    "attributes": [
        {
            "name": "switch",
            "currentValue": "off",
            "dataType": "ENUM",
            "values": [
                "on",
                "off"
            ]
        }
    ],
    "capabilities": [
        "Switch",
        {
            "attributes": [
                {
                    "name": "switch",
                    "dataType": null
                }
            ]
        },
        "Configuration",
        "Refresh",
        "Actuator"
    ],
    "commands": [
        "configure",
        "flash",
        "off",
        "on",
        "refresh",
        "refresh"
    ]
}

使用json映射工具,它为布局定义了

public class Attribute {

@SerializedName("name")
@Expose
private String name;
@SerializedName("currentValue")
@Expose
private String currentValue;
@SerializedName("dataType")
@Expose
private String dataType;
@SerializedName("values")

它定义的单独的类

public class Example {

@SerializedName("id")
@Expose
private String id;
@SerializedName("name")
@Expose
private String name;
@SerializedName("label")
@Expose
private String label;
@SerializedName("attributes")
@Expose
private List<Attribute> attributes = null;
@SerializedName("capabilities")
@Expose
private List<String> capabilities = null;
@SerializedName("commands")
@Expose
private List

设备详细信息类

data class DeviceDetails(
    val attributes: List<Attribute>,
    val capabilities: List<String>,
    val commands: List<String>,
    val id: String,
    val label: String,
    val name: String
)

属性类

data class Attribute(
    val currentValue: String,
    val dataType: String,
    val name: String,
    val values: List<String>
)

接口适配器

interface INetworkAPIDetails {
    @GET("devices/65")
    fun getAllDetails(@Query("access_token") access_token: String): Observable<List<Attribute>>

Adapater

class PostItemDetailsAdapter(private val postdetailsList: List<Attribute>, private val context: Context) :
    RecyclerView.Adapter<PostItemDetailsAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            LayoutInflater.from(context).inflate(R.layout.post_item_details,
                parent, false))
    }

    override fun getItemCount(): Int {
        return postdetailsList.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.itemView.txtPostName.text = this.postdetailsList[position].name
        holder.itemView.txtPostCurrent.text = this.postdetailsList[position].currentValue
        holder.itemView.txtPostDataType.text = this.postdetailsList[position].dataType

    }
    class ViewHolder(view: View) : RecyclerView.ViewHolder(view)
}

Activity2

class Activity2 : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity2)

        //Debugging URL//
        val interceptor : HttpLoggingInterceptor = HttpLoggingInterceptor().apply {
            this.level = HttpLoggingInterceptor.Level.BODY
        }

        val client : OkHttpClient = OkHttpClient.Builder().apply {
            this.addInterceptor(interceptor)
        }.build()
        //Debugging URL//

        Log.d("TAG", "Activity 2")

        val retrofit = Retrofit.Builder().addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .baseUrl("http://xxx.xxx.xxx.xxx/apps/api/109/")
            .client(client)
            .build()
        //Base of API Call//


        //Build List of Devices//
        val postsApi = retrofit.create(INetworkAPIDetails::class.java)
        var response = postsApi.getAllDetails(access_token = "xxxx")

        //Displaying List//
        response.observeOn(AndroidSchedulers.mainThread()).subscribeOn(IoScheduler()).subscribe {
            rv__list_posts_details.adapter = PostItemDetailsAdapter(it, this)
        }
    }
}

1 个答案:

答案 0 :(得分:1)

使用您共享的JSON,您的INetworkAPIDetails应该是:

interface INetworkAPIDetails {
    @GET("devices/65")
    fun getAllDetails(@Query("access_token") access_token: String): Observable<DeviceDetails>
}

该结构似乎为DeviceDetails,加上List表示它在校正Attribute类型的对象数组之前期望对象数组。

此外,您在capabilities数组中遇到了一个棘手的情况:在您的数据结构中将其定义为List<String> ...,但是第二个元素"Switch""Configuration"不是String,而是完整的Object

在这种情况下,请参见How parse json array with multiple objects by gson?Using GSON to parse array with multiple types