预期begin_array但是在第1行第2列改进2的begin_object

时间:2018-04-04 16:03:57

标签: java android json gson retrofit2

我在android中使用retrofit 2从服务器接收json格式的数据并将其用作对象。我正在为服务器端的netbeans工作。但它给了我以上我提到的以下例外。这是我的客户端(Android)代码

Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl("http://192.168.1.6:8080/")
            .addConverterFactory(GsonConverterFactory.create());

    Retrofit retrofit = builder.build();
    DriverClient driver = retrofit.create(DriverClient.class);
    Call<List<Driver>> call = driver.getDriverName();

    call.enqueue(new Callback<List<Driver>>() {
        @Override
        public void onResponse(Call<List<Driver>> call, Response<List<Driver>> response) {
            List<Driver> list = response.body();

            Toast.makeText(MainActivity.this, "Size : " + list.size(), Toast.LENGTH_SHORT).show();

            Driver driver = list.get(0);
            String name = driver.getName();
            Toast.makeText(MainActivity.this, "Name : " + name , Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call<List<Driver>> call, Throwable t) {
            Toast.makeText(MainActivity.this, "Error : " + t.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });

这是Driver class

public class Driver {
    @SerializedName("name")
    private String name;

    public Driver(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

这里是DriverClient接口

public interface DriverClient {
    @GET("/Final/image")
    Call<List<Driver>> getDriverName();
}

这是简单的服务器端代码

JSONObject json = new JSONObject();
json.put("name", "Hafiz Hamza");    
response.setContentType("text/plain");
response.setHeader("chache-control", "no cache");  
PrintWriter out = response.getWriter();
out.println(json);

如何解决此异常

2 个答案:

答案 0 :(得分:0)

您从终端获得object,因此您的应用端需要object(此处您希望来自应用端array

试试这个

Retrofit.Builder builder = new Retrofit.Builder()
        .baseUrl("http://192.168.1.6:8080/")
        .addConverterFactory(GsonConverterFactory.create());

Retrofit retrofit = builder.build();
DriverClient driver = retrofit.create(DriverClient.class);
Call<Driver> call = driver.getDriverName();

call.enqueue(new Callback<Driver>() {
    @Override
    public void onResponse(Call<Driver> call, Response<Driver> response) {
        Driver driver = response.body();

        Toast.makeText(MainActivity.this, "Size : " + list.size(), Toast.LENGTH_SHORT).show();

        String name = driver.getName();
        Toast.makeText(MainActivity.this, "Name : " + name , Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onFailure(Call<Driver> call, Throwable t) {
        Toast.makeText(MainActivity.this, "Error : " + t.getMessage(), Toast.LENGTH_SHORT).show();
    }
});

和你的api界面

public interface DriverClient {
@GET("/Final/image")
Call<Driver> getDriverName();
}

答案 1 :(得分:0)

这意味着响应结果是一个对象,但是您需要列表。  更改通话&gt;致电