简体   繁体   English

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

[英]How to parse JSON data using retrofit and rx?

I'm trying to get the data from JSON using retrofit and rx. 我正在尝试使用翻新和rx从JSON获取数据。 I followed this tutorial . 我遵循了本教程 But the JSON from that tutorial is a little different from mine. 但是该教程中的JSON与我的有所不同。 So I just changed how to parse it a bit. 所以我只是改变了解析方式。 But if I get the JSON or not because I don't know how I know that the JSON is already called or not and in app it didn't show anything. 但是,如果我获取或不获取JSON,是因为我不知道我是否知道已调用JSON,并且在应用程序中它没有显示任何内容。

If anyone knows how it works and how to make the parse, Please guide me. 如果有人知道它如何工作以及如何进行解析,请指导我。

This is my code where I want to parse the JSON data in fragment. 这是我要在其中解析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())
    }
}

This is my interface: 这是我的界面:

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

This is the adapter: 这是适配器:

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)
}

Appreciate your help. 感谢您的帮助。

Your API response have this structure: 您的API响应具有以下结构: 在此处输入图片说明

You need to do more complex model. 您需要做更复杂的模型。 For example you can do TeamResponse class: 例如,您可以执行TeamResponse类:

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

And change INetworkAPI to: 并将INetworkAPI更改为:

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

Then in your fragment: 然后在您的片段中:

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

EDIT: You can see all your api interaction in LogCat (you will can see requests and responses). 编辑:您可以在LogCat中看到所有的api交互(您将看到请求和响应)。 For it add dependency: 为此添加依赖项:

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

And then change retrofit builder: 然后更改改造生成器:

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

getClient() code: 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();
}

And change all Int fields from Team model to String (all of these are String in response). 并将所有Int字段从Team模型更改为String(作为响应,所有这些都是String)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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