Kotlin-预期为BEGIN_OBJECT,但在第1行第2列为BEGIN_ARRAY

时间:2018-07-30 17:32:55

标签: arrays

我正在Kotlin练习一些RecyclerView,并且试图通过使用从网站上获取的NASA API来显示NASA图片的应用程序。然后我从Github上的NASA上看到了these APIs,我决定使用5个或更多条目的那个,这就是我现在遇到的问题。我知道问题是,当应用尝试为此获取字符串或对象列表时,它会面对数组列表,但是老实说,我不知道如何更改代码以获取数组而不是字符串。 您能告诉我如何更改此内容

这是我的代码行:

MainActivity

import android.graphics.Color
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import com.google.gson.GsonBuilder
import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.*
import java.io.IOException

class MainActivity : AppCompatActivity() {

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

        mainRecyclerview.layoutManager = LinearLayoutManager(this)
        mainRecyclerview.adapter = MainAdapter()

        fetchJson()
    }

    private fun fetchJson() {
        val apiKeyUrl = "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&count=5"
        val request = Request.Builder().url(apiKeyUrl).build()
        val client = OkHttpClient()
        client.newCall(request).enqueue(object: Callback{
            override fun onFailure(call: Call?, e: IOException?) {
                println("Failed to Do")
            }

            override fun onResponse(call: Call?, response: Response?) {
                val body = response?.body()?.string()
                println(body)
                val gson = GsonBuilder().create()
                val homeFeed = gson.fromJson(body,HomeFeed::class.java)
            }
        })
    }
}

MainAdapter

import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.recyclerview_row_layout.view.*

class MainAdapter: RecyclerView.Adapter<CustomViewHolder>() {
    val imageTitles = listOf("1st Video", "2nd Video", "3rd Video")

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomViewHolder{
        val layoutInflater = LayoutInflater.from(parent.context)
        val cellForRow = layoutInflater.inflate(R.layout.recyclerview_row_layout, parent,false)
        return CustomViewHolder(cellForRow)
    }

    override fun onBindViewHolder(holder: CustomViewHolder, position: Int) {
        val imageTitle = imageTitles.get(position)
        holder.view.imageTitleTxt.text = imageTitle
    }

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

模型

class HomeFeed(val title: String, val date: String, val explanation: String,
           val hdurl: String, val url: String, val copyright: String)

0 个答案:

没有答案