dusk
dusk

Reputation: 27

Json structure to get data with a GET method android studio retrofit java

I got an error : expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $ What i understand is that retrofit want a BEGIN_ARRAY ? I've found some solutions but don't work for me.

I've tried some solutions that don't work. I think it was the JSON structure which i don't know how to use it.

So for my code : My interface


public interface UserService {

    String ENDPOINT = "http://localhost:3000/";

    @GET("users")
    Call<List<User>> getUsers();

}

Datas


public class User {
    @SerializedName("_id")
    @Expose
    private int _id;

    @SerializedName("name")
    @Expose
    private String name;

    @SerializedName("firstname")
    @Expose
    private String firstname;

    @SerializedName("picture")
    @Expose
    private String picture;


    public int getId() {
        return _id;
    }


    public String getName() {
        return name;
    }


    public String getFirstname() {
        return firstname;
    }


    public String getPicture() {
        return picture;
    }

}

My MainActivity


textViewResult = findViewById(R.id.text_view_result);

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(UserService.ENDPOINT)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        UserService jsonUserService = retrofit.create(UserService.class);
        Call<List<User>> call = jsonUserService.getUsers();


        call.enqueue(new Callback<List<User>>() {
            @Override
            public void onResponse(Call<List<User>> call, Response<List<User>> response) {
                if(!response.isSuccessful()){
                    textViewResult.setText("Code : " + response.code());
                    return;
                }

                List<User> users = response.body();

                for(User user : users){
                    String content = "";
                    content += "ID: " + user.getId() + '\n';
                    content += "FirstName: " + user.getFirstname() + '\n';
                    content += "Name: " + user.getName() + '\n';
                    content += "Picture: " + user.getPicture() + '\n';

                    textViewResult.append(content);
                }
            }

            @Override
            public void onFailure(Call<List<User>> call, Throwable t) {
                textViewResult.setText(t.getMessage());
            }
        });

And my json looks like ..

{
    "users": [
        {
            "_id": 1,
            "name": "test",
            "firstname": "user",
            "picture": "http://localhost:3000/imgs/1.jpg"
        },
        {
            "_id": 2,
            "name": "test1",
            "firstname": "user1",
            "picture": "http://localhost:3000/imgs/2.jpg"
        },
        {
            "_id": 3,
            "name": "test2",
            "firstname": "user2",
            "picture": "http://localhost:3000/imgs/3.jpg"
        },
}

I think it was the "users": which cause this problem. But i don't know how to resolve this.

Thanks a lot if anyone had the solution.

Upvotes: 0

Views: 183

Answers (3)

dusk
dusk

Reputation: 27

@Rajasekaran

My other problem is :


public class User {
    @SerializedName("_id")
    @Expose
    private int _id;

    @SerializedName("name")
    @Expose
    private String name;

    @SerializedName("firstname")
    @Expose
    private String firstname;

    @SerializedName("picture")
    @Expose
    private String picture;

    //Getters
}


public class APIResponse {
    @SerializedName("users")
    @Expose
    private List<User> users = null;

    public List<User> getUsers()
    {return users;}

    public void setUsers(List<User> users)
    {this.users= users;}
}

Here is my MainActivity


        UserService jsonUserService = retrofit.create(UserService.class);
        Call<List<APIResponse>> call = jsonUserService.getUsers();


        call.enqueue(new Callback<List<APIResponse>>() {
            @Override
            public void onResponse(Call<List<APIResponse>> call, Response<List<APIResponse>> response) {
                if(!response.isSuccessful()){
                    textViewResult.setText("Code : " + response.code());
                    return;
                }

                List<User> listUser = null;

                List<APIResponse> users = response.body();

                for(APIResponse user : users){
                    listUSer = user.getUsers();
                }
                for(User user : listUser){
                    String content = "";
                    content += "ID: " + user.getId() + '\n';
                    content += "FirstName: " + user.getFirstname() + '\n';
                    content += "Name: " + user.getName() + '\n';
                    content += "Picture: " + user.getPicture() + '\n';

                    textViewResult.append(content);
                }

                Log.e("MainActivity", "Success : " + listUser);
            }

            @Override
            public void onFailure(Call<List<APIResponse>> call, Throwable t) {
                Log.e("MainActivity", "Failure : " + t);
            }


        });

2019-05-22 14:05:07.983 18425-18425/com.example.user E/MainActivity: Failure : java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

I got the same error :(

Thanks a lot !

Upvotes: 0

Rajasekaran M
Rajasekaran M

Reputation: 2538

your response class should be

class APIResponse{

   @SerializedName("users")
   @Expose
   private List<User> users;

  public List<User> getUsers()
   {return users;}

  public void setUsers(List<User> users)
   {this.users= users;}

}

Interface should be ;

public interface UserService {

String ENDPOINT = "http://localhost:3000/";

@GET("users")
Call<APIResponse> getUsers();

}

you enqueue() method should be :

 call.enqueue(new Callback<APIResponse>() {
        @Override
        public void onResponse(Call<APIResponse> call, Response<APIResponse> response) {
            if(!response.isSuccessful()){
                textViewResult.setText("Code : " + response.code());
                return;
            }

            List<User> users = response.body().getUsers();

            for(User user : users){
                String content = "";
                content += "ID: " + user.getId() + '\n';
                content += "FirstName: " + user.getFirstname() + '\n';
                content += "Name: " + user.getName() + '\n';
                content += "Picture: " + user.getPicture() + '\n';

                textViewResult.append(content);
            }
        }

        @Override
        public void onFailure(Call<List<User>> call, Throwable t) {
            textViewResult.setText(t.getMessage());
        }
    });

Upvotes: 2

garry
garry

Reputation: 429

There is a problem with your Response i.e. User class in your case, that's why this error is shown.

Change your data class (User.java) to ResponseClass.java ::

public class ResponseClass {

@SerializedName("users")
@Expose
private List<User> users = null;

public List<User> getUsers() {
    return users;
}

public void setUsers(List<User> users) {
    this.users = users;
}


public class User {

    @SerializedName("_id")
    @Expose
    private Integer id;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("firstname")
    @Expose
    private String firstname;
    @SerializedName("picture")
    @Expose
    private String picture;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getPicture() {
        return picture;
    }

    public void setPicture(String picture) {
        this.picture = picture;
    }

}

Upvotes: 0

Related Questions