0

I am working on a android studio project with web api. I tried to make login Activity and when I run the app with simulator and it show error java.lang.illegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $

Api Code

[HttpGet]
        public IHttpActionResult getUser(string userName, string passWord)
        {
            List<Person> api = new List<Person>();
            SqlConnection mainconn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString);
            SqlCommand da = new SqlCommand("Select UserID, username, password from tblLogin where charindex(@username, username) = 1 and charindex(@password, password) = 1", mainconn);
            mainconn.Open();
            da.Parameters.Add("@username", SqlDbType.VarChar);
            da.Parameters["@username"].Value = userName.ToString();
            da.Parameters.Add("@password", SqlDbType.VarChar);
            da.Parameters["@password"].Value = passWord.ToString();
            SqlDataReader dr = da.ExecuteReader();
            while(dr.Read())
            {
                api.Add(new Person()
                {
                    UserID = Convert.ToDecimal(dr.GetValue(0)),
                    username = Convert.ToString(dr.GetValue(1)),
                    password = Convert.ToString(dr.GetValue(2))
                });
            }
            return Ok(api);
        }

ApiClient:

public class ApiClient {
    public static Retrofit getRetrofit() {

        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor).build();

        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl("http://XXX.XX.XXX.X/webapi/")
                .client(okHttpClient)
                .build();

        return retrofit;
    }

    public static UserService getService() {
        UserService userService = getRetrofit().create(UserService.class);

        return userService;
    }
}

UserService:

public interface UserService {

    @GET("api/user/")
    Call<LoginResponse> loginUser(@Query("username") String username, @Query("password") String password);
}

Login Activity:

public class MainActivity extends AppCompatActivity {

    Button btnLogin;
    EditText edUsername, edPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnLogin = findViewById(R.id.btnLogin);
        edUsername = findViewById(R.id.etUsername);
        edPassword = findViewById(R.id.etPassword);

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(TextUtils.isEmpty(edUsername.getText().toString()) || TextUtils.isEmpty(edPassword.getText().toString())) {
                    String message = "All inputs required ..";
                    Toast.makeText(MainActivity.this,message,Toast.LENGTH_LONG).show();;
                } else {
                    LoginRequest loginRequest = new LoginRequest();
                    loginRequest.setUsername(edUsername.getText().toString());
                    loginRequest.setPassword(edPassword.getText().toString());
                    loginUser(loginRequest);
                }
            }
        });
    }

    public void loginUser(LoginRequest loginRequest) {
        Call<LoginResponse> loginResponseCall = ApiClient.getService().loginUser(edUsername.getText().toString(), edPassword.getText().toString());
        loginResponseCall.enqueue(new Callback<LoginResponse>() {
            @Override
            public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
                if(response.isSuccessful()) {
                    LoginResponse loginResponse = response.body();
                    startActivity(new Intent(MainActivity.this, Visitor.class).putExtra("data",loginResponse));
                    finish();
                } else {
                    String message = "An error occurred please try again later... ";
                    Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<LoginResponse> call, Throwable t) {
                String message = t.getLocalizedMessage();
                Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
            }
        });
    }
}

android LoginResponse:

public class LoginResponse implements Serializable {

    private String UserID;
    private String username;
    private List<LoginRequest> loginRequests = null;

    public String getUserID() {
        return UserID;
    }

    public void setUserID(String userID) {
        UserID = userID;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public List<LoginRequest> getLoginRequests(){
        return loginRequests;
    }

    public void setLoginRequests(List<LoginRequest> loginRequests) {
        this.loginRequests = loginRequests;
    }
}

LoginRequest:

private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

Api Result:

[{"UserID":1.0,"username":"Steady","password":"test"}]

I have used IHttpActionResult for the web api, I want to remove the Array to make it works, Are there any solution?

1 Answers1

0

The JSON is returning an array but you are expecting an object. Your API result looks like this: [{"UserID":1.0,"username":"Steady","password":"test"}]. This is an object inside an array. What your application needs is an API result that starts with curly braces, hence, an object.

Check the API result and get it to return something that looks like this: { //apiresult }.

Check this links for more information on the same: Retrofit Expected BEGIN_OBJECT but was BEGIN_ARRAY

GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"?

Mwai
  • 41
  • 5