我是初学者。我试图在JSONarray中获取来自POST请求的响应。当我尝试在阵列上获得响应时,我可以获得JSON对象。这是我的POJO
User.Java
public class User {
@SerializedName("username")
@Expose
private String user;
@SerializedName("pass")
@Expose
private String pass;
@SerializedName("status")
@Expose
private String status;
@SerializedName("message")
@Expose
private String message;
@SerializedName("data")
@Expose
private ArrayList<Datum> data;
public User(String user, String pass, String mesaage){
this.user = user;
this.pass = pass;
this.message = message;
}
public String getStatus() {
return status;
}
public ArrayList<Datum> getData() {
return data;
}
public void setData(ArrayList<Datum> data) {
this.data = data;
}
public String getMessage() {
return message;
}
}
Datum.Java:
public class Datum {
@SerializedName("id")
@Expose
private String id;
@SerializedName("username")
@Expose
private String username;
@SerializedName("mk_nama")
@Expose
private String mkNama;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getMkNama() {
return mkNama;
}
public void setMkNama(String mkNama) {
this.mkNama = mkNama;
}
}
这是我的界面
public interface UserClient {
@FormUrlEncoded
@POST("login")
Call<User> loginAccount (
@Field("user") String username,
@Field("pass") String password
);}
这是我的MainActivity
private void sendNetworkRequest(String username, String password) {
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("https://prht.herokuapp.com/api/")
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
UserClient client = retrofit.create(UserClient.class);
Call<User> call = client.loginAccount(username,password);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
Toast.makeText(LoginActivity.this, response.body().getData(),Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<User> call, Throwable t) {
Toast.makeText(LoginActivity.this, "BAD ERROR" , Toast.LENGTH_SHORT).show();
}
});
}
我似乎无法在getData()
中找到JSONarray的对象答案 0 :(得分:0)
我认为这可能有效,但可能你应该改变一些细节。设置一个断点并进行调试,看看Variables中发生了什么。
Data data = response.body().getData();
Datum datum = data.get(0);
Toast.makeText(LoginActivity.this,datum.getUsername() +" , "+ datum.getMkNama(),Toast.LENGTH_SHORT).show();