简体   繁体   English

Android - Moshi 中的多种响应类型

[英]Android - Multiple Response Types in Moshi

I can get the following JSON data from the server :我可以从服务器获取以下 JSON 数据:

{
    "id": 1,
    "groupName": "MyBestFriends"
}

In my Android project, I use Moshi to handle this response.在我的 Android 项目中,我使用Moshi来处理这个响应。 Particularly, I use the following data class for that type of response:特别是,我将以下数据类用于该类型的响应:

@JsonClass(generateAdapter = true)
data class Group(
    val id: Long,
    val groupName:String
)

So, but in case a requested Group does not exist, then I can also get the following JSON response:所以,但如果请求的组不存在,那么我也可以获得以下 JSON 响应:

{
    "detail": "Not found."
}

How, could my Group data class also handle this ?如何,我的 Group 数据类也能处理这个吗? What I want is handling both types of responses but with only one data class ?我想要的是处理两种类型的响应,但只有一个数据类? Is that possible ?那可能吗 ?

Note: When I used Java and GSON in my earlier Android Projects, I could use the @SerializedName annotation for the fields and whatever JSON response came in the GSON adapter mapped that to the given class.注意:当我在早期的 Android 项目中使用 Java 和 GSON 时,我可以对字段使用@SerializedName注释,并且 GSON 适配器中的任何 JSON 响应都将其映射到给定的类。 So, in my case it would be something like this:所以,就我而言,它会是这样的:

public class Group {

    @SerializedName("id")
    private Long id;

    @SerializedName("groupName")
    private String groupName;

    @SerializedName("detail")
    private String detail;

    // getter & setter
}

Is this also possible with Moshi ?这也可以用 Moshi 吗?

Yes!是的! You can use @Json(name="detail") on your field to assign it a name when encoding and decoding.您可以在您的字段上使用@Json(name="detail")在编码和解码时为其分配一个名称。

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

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