2017-08-10 126 views
0

我使用Retrofit 2.我在http://ip.jsontest.com/上使用测试JSON。它非常简单JSON。为什么我会接受这个错误?

在实际的项目中,我也有这个错误,但我想,这是因为我有非常大的JSON。我用你的测试JSON。需要帮助))

java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

这是JSON

{ “IP”: “54.196.188.78” }

我的接口

public interface UmoriliApi { 
    @GET(".") 
    Call<List<Test>> getData(); 
} 

我的测试类

public class Test { 
    @SerializedName("ip") 
    @Expose 
    private String ip; 

    public String getIp() { 
     return ip; 
    } 
    public void setIp(String ip) { 
     this.ip = ip; 
    } 
} 

我的API类

public class App extends Application { 

    private static UmoriliApi umoriliApi; 
    private Retrofit retrofit; 

    @Override 
    public void onCreate() { 
     super.onCreate(); 

     retrofit = new Retrofit.Builder() 
       .baseUrl("http://ip.jsontest.com/") 
       .addConverterFactory(GsonConverterFactory.create()) 
       .build(); 
     umoriliApi = retrofit.create(UmoriliApi.class); 
    } 

    public static UmoriliApi getApi() { 
     return umoriliApi; 
    } 
} 

我的MainActivity类别

public class MainActivity extends AppCompatActivity { 

    private static final String TAG = "TAG"; 
    List<Test> posts; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     posts = new ArrayList<>(); 

     App.getApi().getData().enqueue(new Callback<List<Test>>() { 
      @Override 
      public void onResponse(Call<List<Test>> call, Response<List<Test>> response) { 
       posts.addAll(response.body()); 
       Log.d(TAG, "onResponse: "+posts.size()); 
      } 

      @Override 
      public void onFailure(Call<List<Test>> call, Throwable t) { 
       Log.d(TAG, "onFailure: "); 
      } 
     }); 
    } 
} 
+0

@GET(“。”) 调用 getData();修改此代码 – Akash

+0

@Akash谢谢。但我怎么能得到测试列表? posts.addAll(response.body()); –

回答

2

基本上你期待和数组,但您收到一个JSON对象。

由于阿卡什在评论说:

Call<List<Test>> getData();

List<Test>是当你想到和Array你写的东西。您需要为物体编写Call<Test>测试

您还必须更改回调。

+0

谢谢。我改了@GET(“。”)调用 getData();我如何获得测试列表? –

+2

@SergeyRokitskiy:您的JSON不包含*列表。它有一个JSON对象。如果你想要一个列表,你的Web服务需要返回一个用JSON格式化的列表。 – CommonsWare

相关问题