- 以下是我尝试从中获取数据的 JSON。我需要
使用retrofit2提取并显示名称和类。 3.我尝试了几个站点,但只能直接从数组中获取数据 4.但不是来自对象数组。这将由这段代码形成。
{ "Class1" :{ "A": [ { "name" : "paul", "class" : "first" } ], "B": [ { "name" : "anna", "class" : "second" } ] }, "Class2" :{ "A": [ { "name" : "matthew", "class" : "first" } ], "B": [ { "name" : "joe", "class" : "second" } ] } }
你能告诉我为什么我会进入 onFailure() 方法吗?我的代码有什么问题
public class MainActivity extends AppCompatActivity {
private ListView listView;
private static final String Tag = "com.example";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.bList);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
String API_BASE_URL = "xyz.com";
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(logging);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
ApiInterface client = retrofit.create(ApiInterface.class);
Call<List<Example>> call = client.getdate();
call.enqueue(new Callback<List<Example>>() {
@Override
public void onFailure(Call<List<Example>> call, Throwable t) {
Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_LONG).show();
}
@Override
public void onResponse(Call<List<Example>> call, Response<List<Example>> response) {
if (response.isSuccessful()) {
//Response success. Handle data here
}
else{
//For getting error message
Log.d("Error message",response.message());
//For getting error code. Code is integer value like 200,404 etc
Log.d("Error code",String.valueOf(response.code()));
}
}
});
}
}
示例是我的主类
下面是MyAPIInterface.java
public interface ApiInterface {public interface ApiInterface {
@GET("/sement")
Call<List<Example>> getdate(@Query("date")String date);
}
最佳答案
您的 JSON 无效。但是,对于你的问题,答案是 您必须使用 http://www.jsonschema2pojo.org/ 创建模型来自 JSON,然后使用 GSON 库将 json 数据映射到模型。
引用这个链接你就会明白https://guides.codepath.com/android/Consuming-APIs-with-Retrofit
或者
对于上面的示例,您将获得名称和类别,例如
List<A> alist = mainclass.getClass1().getA();
for (int i = 0; i < alist.size(); i++) {
String name = alist.get(i).getName();
String class = alist.get(i).getClass();
}
对 B 类做同样的事情
关于java - 使用 Retrofit 从最内部类获取数据。帮我显示A类和B类的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42018123/