我正在学习改造。以下是我的 json 响应:
{
"battingStyle": "Right-hand bat",
"born": "April 24, 1973, Bombay (now Mumbai), Maharashtra",
"bowlingStyle": "Right-arm offbreak, Legbreak googly",
"country": "India",
"creditsLeft": 248,
"currentAge": "44 years 186 days",
"data": {
"batting": {
"tests": {
"50": "68",
"100": "51",
"4s": "",
"6s": "69",
"Ave": "53.78",
}
}
},
"playingRole": "Top-order batsman",
}
我正在尝试将“测试”部分的值分配给 Tests
POJO类。
但是所有字段都被初始化为 null。我哪里出错了?
我的界面代码:
public interface ApiInterface {
@GET("playerStats")
Call<PlayerData> getPlayerData(@Query("apikey")String apikey, @Query("pid") String pid);
我的 MainActivity
中的代码
ApiInterface apiInterface = r.create(ApiInterface.class);
Call<ODIs>call=apiInterface.getODIStats("apikey","pid");
call.enqueue(new Callback<MatchData>() {
@Override
public void onResponse(Call<PlayerData> call, Response<PlayerData> response) {
try {
JSONObject jsonObject = new JSONObject(newGson().toJson(response.body()));
s=jsonObject.toString();
Tests tests = new Gson().fromJson(s, Tests.class);
}
catch (Exception e){}
在这里,r
是Retrofit
实例。如果我的代码是多余的,我很抱歉。我刚开始学习。如果我必须提供更多详细信息,请告诉我。
最佳答案
您必须通过每个级别,在本例中,首先是 data
对象,然后是 batting
对象,最后是 tests
对象。
JSONObject jsonObject = new JSONObject(newGson().toJson(response.body()));
JSONObject testsObj = jsonObject.getJSONObject("data").getJSONObject("batting").getJSONObject("tests");
Tests tests = new Gson().fromJson(testsObj.toString(), Tests.class);
请注意,为了使其正常工作,您必须使用 SerializedName
注释来标记 JSON 中的每个字段的名称,因为变量名称不可能以数字开头:
import com.google.gson.annotations.SerializedName;
public class Tests{
@SerializedName("50")
private String fifteen;
@SerializedName("100")
private String hundred;
@SerializedName("4s")
private String fourS;
@SerializedName("6s")
private String sixS;
private String Ave;
}
关于android - 从 Android 中的 JSON 响应访问嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58567183/