如何使用Klaxon解析嵌套的JSON并在recyclerview中显示?

时间:2018-08-28 02:22:18

标签: android android-recyclerview kotlin nestedrecyclerview klaxon

这是我的MainActivity.kt

class MainActivity : AppCompatActivity() {

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

    var data = Klaxon()
            .parseArray<ProductData>(readArray())
    if(!data!!.isEmpty()) {
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.hasFixedSize()
        recyclerView.adapter = ListAdapter(data, { partItem : ProductData -> partItemClicked(partItem)})
    }
}

private fun partItemClicked(partItem : ProductData) {
    Toast.makeText(this, "You click ${partItem.title}", Toast.LENGTH_SHORT).show()

    val showDetailActivityIntent = Intent(this, DetailProduct::class.java)
    showDetailActivityIntent.putExtra(Intent.EXTRA_TEXT, partItem.title)
    startActivity(showDetailActivityIntent)
}

private fun readArray(): String {
    return application.assets.open("products.json").bufferedReader().use {
        it.readText()
    }
}

这是我的适配器ListAdapter.kt

class ListAdapter (var catalogList: List<ProductData>, var clickListener: (ProductData) -> Unit) :
    RecyclerView.Adapter<RecyclerView.ViewHolder>() {

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
    var v = LayoutInflater.from(parent.context).inflate(R.layout.product_catalog_list, parent, false)
    return ListHolder(v)
}

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
    (holder as ListHolder).bind(catalogList[position], clickListener)
}

override fun getItemCount() = catalogList.size

class ListHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    fun bind(_list: ProductData, clickListener: (ProductData) -> Unit) {
        itemView.nama_produk.text = _list.title
        itemView.deskripsi_produk.text = _list.snip
        itemView.harga.text = _list.calc.toString()
        itemView.setOnClickListener { clickListener(_list) }
    }
}

我的JSON文件products.json

{
    "snippets": [
      {
        "title": "Huben Tarikan Laci Sabit TH-211",
        "snip": "Handle lemari atau laci dapat memudahkan penggunaan pada furniture rumah dengan ukuran yang bervariasi, desain&nbsp;..<br \/>",
        "calc": 0
      },
      {
        "title": "Huben Rak Piring Stainless RP + Ukuran",
        "snip": "Huben rak piring dengan bahan stainless berkualitas sangat awet dan tahan lama ideal untuk keperluan dapur anda Huben&nbsp;..<br \/>",
        "calc": 0
      },
      {
        "title": "Huben Tarikan Laci TA-24 ",
        "snip": "Tarikan laci huben berbahan stainless steel sangat awet dan tahan lama serta simple, gunakan tarikan ini sebagai&nbsp;..<br \/>",
        "calc": 0
      },
      {
        "title": "Yane A 910 Handle Laci Wooden \/ Tarikan Laci ",
        "snip": " Tarikan laci kayu tidak pernah kalah dengan bahan stainless karena mampu mempercantik tampilan laci atau lemari.&nbsp;..<br \/>",
        "calc": 0
      },
      {
        "title": "Yane B - I006C Kitchen Set \/ Rak Dapur ",
        "snip": " Ayo gunakan rak dapur kitchen set untuk menjaga kerapihan pada dapur Rak dapur minimalis sebagai tempat untuk&nbsp;..<br \/><span class=\"priOffi\">Rp 549.000<\/span><small class=\"unit\"> \/ item<\/small>",
        "calc": 0
      },
      {
        "title": "Yane AI 002 L Kitchen Set \/ Rak Dapur ",
        "snip": " Ayo beli dan gunakan rak dapur untuk menyimpan stok makanan agar rapi dan aman Rak dapur solusi untuk menyimpan barang&nbsp;..<br \/><span class=\"priOffi\">Rp 4.399.000<\/span><small class=\"unit\"> \/ item<\/small>",
        "calc": 0
      }
      ]
}

我应该如何在 klaxon()中调用嵌套在“代码段”中的“标题”?

数据类如何?我应该声明什么? 我不明白如何使用recyclerview显示功能(尤其是使用Klaxon)在嵌套JSON中调用数据。

1 个答案:

答案 0 :(得分:0)

您的数据类将是

data class ProductData(val snippets: List<SnippetsItem>?)
data class SnippetsItem(val snip: String = "",
                    val calc: Int = 0,
                    val title: String = "")

和解析器json

val jsonFile= assets.open("myjson.json")

val result = Klaxon().parse<ProductData>(InputStreamReader(jsonFile))

val list = result?.snippets ?: emptyList()

这是列表。您将此列表发送到您的回收者视图适配器。修改您的适配器

class ListAdapter(var catalogList: List<SnippetsItem>, var clickListener: ClickListener)
: RecyclerView.Adapter<ListAdapter.ListHolder>() {


interface ClickListener {
    fun click(snip: SnippetsItem)
}

inner class ListHolder(itemView: View) : RecyclerView.ViewHolder(itemView),
        View.OnClickListener {
    override fun onClick(v: View?) {
        val pos = adapterPosition
        clickListener.click(catalogList[pos])
    }

    fun bind(snip: SnippetsItem) {
        //bind with view
        itemView.setOnClickListener(this)
    }

}
}

现在是主要活动

class MainActivity : AppCompatActivity(),ListAdapter.ClickListener {



    override fun click(snip: SnippetsItem) {
        //do whatever you want
    }
}