使用Kotlin中的改造来解析JSON对象

时间:2019-02-13 18:02:19

标签: android json kotlin retrofit

我正在尝试使用Kotlin中的翻新库显示json数据

这是我的杰森:

[
  {
    "login": "mojombo",
    "id": 1,

  },
  {
    "login": "defunkt",
    "id": 2,
    }
]

我的主要活动

 call.enqueue(object : Callback<UserResponse> {
        override fun onResponse(call: Call<UserResponse>, response: Response<UserResponse>) {
            Log.e("list","list")
            val countrylist = response.body()
            for (size in response.body()) {
                System.out.println(size.toString())
            }

            // var listOfMovies: List<UserResponse> = response.body()?.results!!
           // myCustomAdapter = UserListAdapter(applicationContext, listOfMovies)
          //  recyclerView.setAdapter(myCustomAdapter)
            progressBar.visibility = View.GONE
        }

        override fun onFailure(call: Call<UserResponse>?, t: Throwable?) {
            progressBar.visibility = View.GONE
            Log.e("list", t.toString())
        }
    })

2 个答案:

答案 0 :(得分:2)

这是我在Kotlin中使用改造和rxjava使用测试API以最佳方式构建的一个应用程序。

型号

data class Post( val userID:Int, val title:String, val body: String)

改装包

IMyApi接口

interface IMyApi {

@get:GET("posts")
val posts: Observable<List<Post>>
}

RetrofitClient对象类

object RetrofitClient {


val instance: Retrofit by lazy {
    Retrofit.Builder()
        .baseUrl("https://jsonplaceholder.typicode.com/")
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .addConverterFactory(GsonConverterFactory.create())
        .build()
 }
}

适配器包

PostAdapter类

  class PostAdapter(private val context: Context, private val postList: List<Post>)
                :RecyclerView.Adapter<PostViewHolder>()
            {
                override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): 
   PostViewHolder {
                    val itemView = LayoutInflater.from(parent.context)
                        .inflate(R.layout.post_item, parent, false)
                    return PostViewHolder(itemView)
                }

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

                   override fun onBindViewHolder(holder: PostViewHolder, position: Int) 
    {
                    holder.userId.text = postList[position].userID.toString()
                    holder.title.text = postList[position].title
                    holder.body.text = StringBuilder(postList[position].body.substring(0,20))
                        .append("...").toString()
                }
            }

PostViewHolder类

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

var userId = itemView.txtID
var title = itemView.txtTitle
var body = itemView.txtBody
}

MainActivity

  class MainActivity : AppCompatActivity() {

                    private lateinit var jsonApi: IMyApi
                    private var compositeDisposable: CompositeDisposable = CompositeDisposable()

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

                        // Init api
                        val retrofit = RetrofitClient.instance
                        jsonApi = retrofit.create(IMyApi::class.java)


                        // View
                        recycler_posts.layoutManager = LinearLayoutManager(this)
                        recycler_posts.setHasFixedSize(true)
                        fetchData()
                    }

                    private fun fetchData() {
                        compositeDisposable.add(jsonApi.posts
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe { posts->displayData(posts)})
                    }

                    private fun displayData(posts: List<Post>?) {
                        val adapter = PostAdapter(this, posts!!)
                        recycler_posts.adapter = adapter
                    }
                }

使用上面显示的方法应该可以帮助您解决问题。另外,在代码中遇到“ recycler_posts”。这是在activity_main中添加的回收站的ID。如果您需要我包括此信息,请告诉我

答案 1 :(得分:0)

这就是我们应用程序中的内容

object GetFAQsAPI {

private val LOG_TAG = GetFAQsAPI.javaClass.simpleName

interface ThisCallback {

    fun onSuccess(getFAQs: GetFAQs)

    fun onFailure(failureMessage: String)

    fun onError(errorMessage: String)
}

/* POST */
fun postData(jo: JsonObject, callback: GetFAQsAPI.ThisCallback) {
    val call = Service.getService().get_faqs(jo)
    call.enqueue(object : Callback<JsonObject> {

        override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) {

            //Log.e(LOG_TAG, response.body().toString());

            try {
                if (response.body()?.get("success")!!.asBoolean) {

                    val gson = GsonBuilder().setPrettyPrinting().create()
                    val getFAQs = gson.fromJson(response.body(), GetFAQs::class.java)

                    callback.onSuccess(getFAQs)

                } else {
                    Log.e(LOG_TAG, "else")

                    val error = response.body()!!.get("err").asString

                    callback.onError(error)
                }

            } catch (e: Exception) {
                Log.e(LOG_TAG, "exception" + e.localizedMessage)

                callback.onFailure(e.message!!)
            }

        }

        override fun onFailure(call: Call<JsonObject>, t: Throwable) {
            Log.e(LOG_TAG, "onFailure: " + t.message)

            callback.onFailure(t.message!!)

        }
    })

}

}

这就是我们从片段中调用它的方式-getFAQs是解析的对象。

private fun getFAQsAPI() {

    showLoading(true)

    val jo = JsonObject().apply {
        addProperty("faq_category", "admin")
    }

    GetFAQsAPI.postData(jo, object : GetFAQsAPI.ThisCallback {
        override fun onSuccess(getFAQs: GetFAQs) {
            Log.i(LOG_TAG, "onSuccess")

            showLoading(false)

            updateUI(getFAQs)
        }

        override fun onFailure(failureMessage: String) {
            Log.e(LOG_TAG, failureMessage)
        }

        override fun onError(errorMessage: String) {
            Log.e(LOG_TAG, errorMessage)
        }
    })
}

希望有帮助。