Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Error "java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $"

public interface UserService {
    @POST(Constants.Api.URL_REGISTRATION)
    @FormUrlEncoded
    BaseWrapper registerUser(@Field("first_name") String firstname, @Field("last_name") String lastname, @Field("regNumber") String phone, @Field("regRole") int role);


 public BaseWrapper registerUser(User user) {
        return getUserService().registerUser(user.getFirstName(), user.getLastName(), user.getPhone(), user.getRole());
    }

This create Exception

 com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

Big thanks for help.

like image 781
androidAnonDev Avatar asked Jul 15 '15 07:07

androidAnonDev


2 Answers

Let's look at the error you are receiving.

Expected BEGIN_OBJECT

Your JSON is an object, and all JSON objects are enclosed in curly braces ({}). BEGIN_OBJECT is therefore {. And it's expecting it somewhere.

but was STRING

But instead he found a string "Something". Still doesn't tell us where.

at line 1 column 1 path $

Ah, perfect. At line 1 column 1. Which is the start of the JSON. So you have forgotten to enclose the whole thing in {} (or at least you have forgotten the first one, but I bet you've forgotten them both).

like image 66
Astrogat Avatar answered Sep 19 '22 12:09

Astrogat


Recently i'd faced similiar issue and solutioned only by adding "Accept: application/json" into header section. So, if you're using retrofit 2.0;

1st solution: For post method add headers parameter like below;

@Headers({"Accept: application/json"})
@POST(Constants.Api.URL_REGISTRATION)
@FormUrlEncoded
BaseWrapper registerUser(@Field("first_name") String firstname, 
                         @Field("last_name") String lastname, 
                         @Field("regNumber") String phone, 
                         @Field("regRole") int role);

2nd solution: Add header into your interceptor class like this;

NB: Code is in kotlin

private fun getInterceptor(): Interceptor {
        try {
            return Interceptor {
                val request = it.request()
                it.proceed(
                    request.newBuilder()
                        .header("Accept", "application/json")
                        .header("Authorization", "$accessTokenType $accessToken")
                        .build()
                )
            }
        } catch (exception: Exception) {
            throw Exception(exception.message)
        }
    }
}

Hope it helps, happy coding :)

like image 26
Rezwan Avatar answered Sep 23 '22 12:09

Rezwan