简体   繁体   中英

How to parse Json in Kotlin MVVM Data binding

I'm trying it implement following Json string:

{ 
   "msg":[ 
      "football",
      "cricket",
      "baseball",
      "rugby",
      "gulf"
],
   "status":"success"
}

I have created the data classes as below:

class Sports(

    val msg : List<String>,
    val status : String
)

And

class Msg (

    val football : List<String>,
    val cricket : List<String>,
    val baseball : List<String>,
    val rugby : List<String>,
    val gulf : List<String>
)

Now I'm trying to get the objects and view it in a recyclerview list as per the tutorial.

How could I change it below & call it in the adapter?

interface PostApi {
    /**
     * Get the list of the pots from the API
     */
    @GET("/posts")
    fun getPosts(): Observable<List<Post>>
}

Edit:

MY adapter class as below:

    class PostListAdapter: RecyclerView.Adapter<PostListAdapter.ViewHolder>() {
        private lateinit var postList:Sports

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostListAdapter.ViewHolder {
            val binding: ItemPostBinding = DataBindingUtil.inflate(LayoutInflater.from(parent.context), R.layout.item_post, parent, false)
            return ViewHolder(binding)
        }

        override fun onBindViewHolder(holder: PostListAdapter.ViewHolder, position: Int) {
            holder.bind(postList)
        }

        override fun getItemCount(): Int {
//Getting error in .isInitialied 'Unresolved reference'
            return if(::postList.isInitialized) postList.message.size else 0
        }

        fun updatePostList(postList: Sports){
            this.postList = postList
            notifyDataSetChanged()
        }

        class ViewHolder(private val binding: 
ItemPostBinding):RecyclerView.ViewHolder(binding.root){ //Getting error in root 'Unresolved reference'
            private val viewModel = PostViewModel()

            fun bind(post: Sports){
                viewModel.bind(post) //Getting error saying No value passed for parameter 'position'
                binding.viewModel = viewModel
            }
        }
    }

If you get the Json from server then call it like below:

interface SportsApi {
    /**
     * Get the Sports from the API
     */
    @GET("/sports")
    fun getSports(): Observable<Sports>
}

Or if you want to to check it in locally then you have to convert this Json

Using Gson :

val sports = Gson().fromJson(json, Sports::java.class)

Using Moshi :

val sports = Moshi.Builder().build().adapter(Sports::java.class).fromJson(json)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM