android - 想要在 retrofitV2 中设置字符串或 TextView 中的 ArrayList 名称
问题描述
我有json响应
{
"status": "success",
"suggestion": {
"message": {
"message_a":"a",
"message_b":"b"
},
"message1": {
"message_a":"a",
"message_b":"b"
},
"message2": {
"message_a":"a",
"message_b":"b"
}
}
}
我想将响应中的“消息”和“消息 2”设置为 RetrofitV2 中的 String 或 TextView
ApiInterface 类
public interface ApiInterface {
@GET(“url”)
Call<Contributor>getCheck();
}
贡献者
public class Contributor {
@SerializedName("status")
String status;
@SerializedName("suggestion")
ArrayList<Suggestion_List>suggestion;
public String getName() {
return name;
}
public ArrayList<Suggestion_List> getSuggestion() {
return suggestion;
}
}
这是我已经完成的代码
解决方案
因此,如果您无法更改响应,"message": {},"message": {},"message": {}
那么解析为 JSONObject 是唯一的方法。
首先创建:
public class Message {
@SerializedName("message_a")
private String message_a;
@SerializedName("message_b")
private String message_b;
public Message(String message_a, String message_b) {
this.message_a = message_a;
this.message_b = message_b;
}
public String getMessage_a() {
return message_a;
}
public void setMessage_a(String message_a) {
this.message_a = message_a;
}
public String getMessage_b() {
return message_b;
}
public void setMessage_b(String message_b) {
this.message_b = message_b;
}
}
}
public interface ApiInterface {
@GET("url")
Call<JSONObject> getCheck();
}
最后在你的活动中
private ApiInterface apiInterface;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
Call<JSONObject> call = apiInterface.getCheck();
call.enqueue(new Callback<JSONObject>() {
@Override
public void onResponse(Call<JSONObject> call, Response<JSONObject> response) {
try {
JSONObject suggestion = response.body().getJSONObject("suggestion");
Message message = new Message(suggestion.getJSONObject("message").getString("message_a"),
suggestion.getJSONObject("message").getString("message_b"));
Message message1 = new Message(suggestion.getJSONObject("message1").getString("message_a"),
suggestion.getJSONObject("message1").getString("message_b"));
Message message2 = new Message(suggestion.getJSONObject("message2").getString("message_a"),
suggestion.getJSONObject("message2").getString("message_b"));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<JSONObject> call, Throwable t) {
}
});
}
然后将文本设置为 TextView
textView.setText(message.getMessage_a());
textView.setText(message.getMessage_b());
推荐阅读
- javascript - 显示一个弹出窗口,其中包含来自 react.js 中的一个表的元素及其总数的信息
- excel - 有没有办法突出显示第一列中具有相同数字的行?
- junit - 如何使用 junit-jupiter 和 junit-vintage 配置文件创建 maven 构建
- r - 如何在 R 中检查 ARIMAmodel 的 AIC
- mysql - 如何在 MAMP 更新和 Symfony 4 安装后进行迁移?
- css - 通过 react: currentColor 从 CSS 变量加载 svg
- javascript - 如何在仍然能够下载其内容的同时阻止元素跳转到新页面?
- code-coverage - Devpartner Coverage 报告第 3 方工具
- c# - 使用字符串、int 数组反序列化 json - .net core C#
- angular6 - 由于安全策略指令,ReCAPTCHA2 脚本加载错误