使用Gson库将JSON数组转换为Java对象或字符串。以下是示例代码:
public class MyObject {
private String name;
private int age;
// getters and setters
public interface MyApi {
@GET("my-endpoint")
Call<List<MyObject>> getMyObjects();
// create Retrofit instance
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
// create API service
MyApi myApi = retrofit.create(MyApi.class);
// make API call
Call<List<MyObject>> call = myApi.getMyObjects();
call.enqueue(new Callback<List<MyObject>>() {
@Override
public void onResponse(Call<List<MyObject>> call, Response<List<MyObject>> response) {
List<MyObject> myObjects = response.body();
// convert List<MyObject> to JSON string
Gson gson = new Gson();
String jsonString = gson.toJson(myObjects);
@Override
public void onFailure(Call<List<MyObject>> call, Throwable t) {
// handle failure