改造2:如何处理动态响应 [英] Retrofit 2: How to handle dynamic response

查看:146
本文介绍了改造2:如何处理动态响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从此API获取数据: http://www.omdbapi.com/
我正在使用Retrofit 2,并为第一个json创建了一个pojo。我很好奇的是当数据不可用时,如何将我的pojo转换为第二个。

I am trying fetch data from this api: http://www.omdbapi.com/ I am using Retrofit 2 and created a pojo for first json. The thing I am curious about is how to convert my pojo to second one when data is not available.

当有数据可用时,它返回这个json:

When there is data available, It returns this json:

http://www.omdbapi.com/?t =西装

{
Title: "Suits",
Year: "2011–",
Rated: "TV-14",
Released: "23 Jun 2011",
Runtime: "44 min",
Genre: "Comedy, Drama",
Director: "N/A",
Writer: "Aaron Korsh",
Actors: "Gabriel Macht, Patrick J. Adams, Rick Hoffman, Meghan Markle",
Plot: "On the run from a drug deal gone bad, Mike Ross, a brilliant college-dropout, finds himself a job working with Harvey Specter, one of New York City's best lawyers.",
Language: "English",
Country: "USA",
Awards: "7 nominations.",
Poster: "http://ia.media-imdb.com/images/M/MV5BMTk1MjYzOTU2Nl5BMl5BanBnXkFtZTgwMzAxMTg5MTE@._V1_SX300.jpg",
Metascore: "N/A",
imdbRating: "8.7",
imdbVotes: "244,979",
imdbID: "tt1632701",
Type: "series",
totalSeasons: "6",
Response: "True"
}

当没有数据可用时,它返回此json:

When there is no data avilable, it returns this json:

http://www.omdbapi.com/?t=asdasdas

{
Response: "False",
Error: "Movie not found!"
}


推荐答案

您有几个选项。在我的头脑中,最简单的一个是在原始pojo中包含错误字段,并始终检查字段响应 。当这是真比所有其他领域将存在。当False时,只有错误字段将在那里。

You have a couple of options. Out of my head the simplest one is to include the Error field in the original pojo and always check for the field Response. When this is "True" than all the other fields will be present. When "False", only the Error field will be there.

另一个选项,也许是最不灵活和可理解的是从您可以继承的pojo 错误。您仍然必须检查 Response 的值来检查是否有错误。我个人会在这里避免这种选择,但我认为很高兴知道你仍然可以做到这一点。这样的事情:

Another option and perhaps the least flexible and understandable is to have a pojo Error from where you can inherit. You'd still have to inspect the value of Response to check if there's an error. I personally would avoid this option here, but I thought it's good to know you can still do it. Something like this:

class Error {
  @SerializedName("Error")
  @Expose
  private String error;
  // ...
}

class Movie extends Error {
  // other fields here
}

你可以看到这是很丑,但是... ...

As you can see this is pretty ugly, but works...

可以尝试的第三个选项是检查Http状态码。这一个取决于API。如果api返回Http代码200即使有错误,那么这不是那么直接。但是,这是我最喜欢的,因为它在我看来更为正确。

A third option you can try is to check the Http status code. This one depends on the API. If the api returns Http code 200 even when there's an error, then this is not that straight forward. However it's my favourite since it provides more correctness in my opinion.

当没有数据时,说api返回Http 404。然后,您可以检查此状态并使用其他pojo来排序错误主体(pojo可能只是错误消息)。如果您使用内置回调中的改装,则必须在 onResponse 上执行此操作。如果您正在使用 RxJava ,那么这更直接,您可以在 onError 方法中轻松实现(所有非2XX http响应都位于 onError 方法中)。

Say the api return Http 404 when there's no data. You can then check this status and use a different pojo to deserialise the error body (The pojo could simply be the error message). If you're using retrofit with the built in Callbacks you'd have to do this on onResponse. If you're using RxJava, then this is even more straight forward as you can do it easily in the onError method (All non-2XX http responses land in the onError method).

您可以使用 errorBody 。您可以使用 Gson 或仅使用此代码段将其转换为pojo:

You can access the error body of a retrofit response with errorBody. You can convert it to a pojo using Gson or simply using this snippet:

Converter<ResponseBody, MyError> converter = new GsonConverterFactory()
   .responseBodyConverter(MyError.class, Annotation[0]);
MyError error = converter.convert(response.errorBody());

(这里 MyError 将是pojo包含错误字段)。

(Here MyError would be the name of the pojo containing the error fields).

您可能只想创建一个转换器工厂。最可能应该是创建 Retrofit 实例时使用的。

You might want to create the converter factory only once. Most probably should be the one you used when creating the Retrofit instance.

如果您实际使用 RxJava 您可以检查我的答案这里关于如何在Rx响应中访问错误体

If you're actually using RxJava you can check my answer here on how to access the error body in an Rx response

这篇关于改造2:如何处理动态响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆