问题
How to extract the value of "text" by using GSON/Retrofit?
{
code: 200,
lang: "en-ms",
text: [
"Burung"
]
}
回答1:
1 Create your model class
public class ResponseItem {
/**
* code : 200
* lang : en-ms
* text : ["Burung"]
*/
private int code;
private String lang;
private List<String> text;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public List<String> getText() {
return text;
}
public void setText(List<String> text) {
this.text = text;
}
}
2 inside your Retrofit method response :
if (response.isSuccessful()) {
ResponseItem responseItem;
responseItem = response.body(); }
and you can call text by saying responseitem.Get("whatever u want from the model class")
回答2:
text there like Map. You need to create pojo with
@SerializedName("code")
@Expose
private int mCode;
@SerializedName("lang")
@Expose
private String mLang;
@SerializedName("text")
@Expose
private Map <String, List<String> mText;
Create Retrofit with factory (GsonFactory). And instantiate this pojo.
p.s: also you can make serializator and deserializator for your objects
回答3:
make POJO class of given response and register this in retrofit callback and get values with the help of getters and setters.
回答4:
you can get all of object in a json and put to a array with this code:
JSONArray texts = new JSONObject(json).getJSONArray("text");
来源:https://stackoverflow.com/questions/52576568/how-to-get-the-value-with-gson-retrofit