使用地图数据从服务器解析JSON

时间:2018-12-07 09:54:17

标签: android json kotlin

我目前正在使用 Retrofit Kotlin 构建应用。到目前为止,我可以从办公服务器解析JSON。但是,现在我在映射数据时遇到了问题。我已经读过有关Kotlin地图的信息,但并不能完全理解。对于服务器上的JSON,我无法上传它,因为公司数据具有保密性。因此,我将使用虚拟JSON,但结构与我公司的JSON相同。在这里:

{"market":
   "101":
      {"name": "xxx",
       "image": "/folderPath/imageName.jpg"
      }
   "102":
      {"name": "yyy",
       "image": "/folderPath/image2Name.jpg"
      }
}

关于数据类,我使用List <>初始化数据类,这里是:

data class Product(
  @SerializedName("Market") val Market: List<MarketContent> = listOf()
)

data class MarketContent(
  @SerializedName("Name") val Name: String,
  @SerializedName("Image") val Image: String
)

我在RecyclerView适配器中尝试过的操作是这样的:

class OtherProductAdapter(private val otherProductList: List<MarketContent>, private val clickListener: (MarketContent) -> Unit) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {

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

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
    (holder as ListOther).bindItem(otherProductList[position], clickListener)
}

override fun getItemCount() = otherProductList.size

class ListOther(itemView: View) : RecyclerView.ViewHolder(itemView){

    private val rImg = itemView.findViewById<ImageView>(R.id.rv_image)

    fun bindItem(t: MarketContent, clickListener: (MarketContent) -> Unit){
        itemView.rv_title.text = t.Name
        Glide.with(itemView.context).load("http://192.168.1.100:3232" +t.Image).into(rImg)
        itemView.setOnClickListener {clickListener(t)}
    }
}
}

这是我的改造

private fun getInto() {
    val apiService = ProductApiService()
    disposable =
            apiService.syncData()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    { result -> intoData(result) },
                    { error -> Log.e("Error", error.message) }
                )
}

private fun intoData(result: Product) {
    rv_view?.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
    rv_view?.hasFixedSize()
    rv_view?.adapter = OtherProductAdapter(result.Market, { item: MarketContent -> clickedItem(item) })
}

结果,我的应用程序未显示任何数据,并显示一条消息:

  

E /错误:java.lang.IllegalStateException:预期为BEGIN_ARRAY,但在行1列109719路径$ .Market处为BEGIN_OBJECT

帮助我如何映射JSON数据。预先感谢。

1 个答案:

答案 0 :(得分:0)

似乎您需要像这样更改映射

@SerializedName("Market") val Market: Map<String, MarketContent> = mapOf()