如何使用翻新和rx解析JSON数据?

时间:2018-10-30 01:23:21

标签: android kotlin rx-java retrofit2 reactivex

我正在尝试使用翻新和rx从JSON获取数据。我关注了this tutorial。但是该教程中的JSON与我的有所不同。所以我只是改变了解析方式。但是,如果我获取或不获取JSON,是因为我不知道我是否知道已调用JSON,并且在应用程序中它没有显示任何内容。

如果有人知道它是如何工作的以及如何进行解析,请指导我。

这是我的代码,我想在其中解析JSON数据。

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    rv__list_posts?.layoutManager = LinearLayoutManager(this.requireContext())

    val retrofit = Retrofit.Builder().addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .baseUrl("https://www.thesportsdb.com/").build()

    val postsApi = retrofit.create(INetworkAPI::class.java)

    var response = postsApi.getAllPosts()

    response.observeOn(AndroidSchedulers.mainThread()).subscribeOn(IoScheduler()).subscribe {
        rv__list_posts.adapter = MainAdapter(listOf(it), this.requireContext())
    }
}

这是我的界面:

interface INetworkAPI {
  @GET("api/v1/json/1/eventslast.php?id=133602")
  fun getAllPosts(): Observable<Team>
}

这是适配器:

class MainAdapter(val postList: List<Team>, val context: Context) :
  RecyclerView.Adapter<MainAdapter.ViewHolder>() {

  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): 
  ViewHolder {
    return 
    ViewHolder(LayoutInflater.from(context).inflate(R.layout.item_layout,parent,false))
  }

  override fun getItemCount(): Int {
      return 10
  }

  override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    holder.itemView.home_team.text = postList.get(position).homeTeam
    holder.itemView.home_score.text = postList.get(position).homeScore.toString()
    holder.itemView.away_team.text = postList.get(position).awayTeam
    holder.itemView.away_score.text = postList.get(position).awayScore.toString()
  }
  class ViewHolder(view: View) : RecyclerView.ViewHolder(view)
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您的API响应具有以下结构: enter image description here

您需要执行更复杂的模型。例如,您可以进行TeamResponse类:

data class TeamResponse(var results: List<Team>)

然后将INetworkAPI更改为:

interface INetworkAPI {
  @GET("api/v1/json/1/eventslast.php?id=133602")
  fun getAllPosts(): Observable<TeamResponse>
}

然后在您的片段中:

response
   .observeOn(AndroidSchedulers.mainThread())
   .subscribeOn(IoScheduler())
   .subscribe {
      rv__list_posts.adapter = MainAdapter(it.results, this.requireContext())
   }

编辑: 您可以在LogCat中查看所有api交互(您可以查看请求和响应)。为此添加依赖项:

 implementation "com.squareup.okhttp3:logging-interceptor:3.9.1"

然后更改改造生成器:

val retrofit = Retrofit.Builder().addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .baseUrl("https://www.thesportsdb.com/")
        .client(getClient())
        .build()

getClient()代码:

private fun getClient(): OkHttpClient {
    val clientBuilder = OkHttpClient.Builder();
    if (BuildConfig.DEBUG) {
        val loggingInterceptor = HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        clientBuilder.addInterceptor(loggingInterceptor);
    }
    return clientBuilder.build();
}

然后将所有Int字段从Team模型更改为String(作为响应,所有这些字段均为String)。