35

I am using retrofit:2.0.0-beta4 for my android app.

I tried to add a user with Retrofit, the user is correctly created in Database, however I got the following error:

03-14 06:04:27.731 30572-30600/com.lehuo.lehuoandroid D/OkHttp: CALLING POST SP_User_CreateUser....your new user_id:48
{"data":{"user_id":"48","nickname":null,"password":null,"status":null},"status":1,"msg":"OK"}
03-14 06:04:27.731 30572-30600/com.lehuo.lehuoandroid D/OkHttp: <-- END HTTP (147-byte body)
03-14 06:04:27.732 30572-30600/com.lehuo.lehuoandroid E/My Jobs: error while executing job
     com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $
         at com.google.gson.stream.JsonReader.syntaxError(JsonReader.java:1573)
         at com.google.gson.stream.JsonReader.checkLenient(JsonReader.java:1423)
         at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:587)
         at com.google.gson.stream.JsonReader.peek(JsonReader.java:429)
         at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:202)
         at com.google.gson.TypeAdapter.fromJson(TypeAdapter.java:260)
         at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:32)
         at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:23)
         at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:213)
         at retrofit2.OkHttpCall.execute(OkHttpCall.java:177)
         at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:87)
         at com.lehuo.lehuoandroid.async.NetworkJob.callNet(NetworkJob.java:30)
         at com.lehuo.lehuoandroid.async.CreateUserJob.onRun(CreateUserJob.java:34)
         at com.path.android.jobqueue.BaseJob.safeRun(BaseJob.java:108)
         at com.path.android.jobqueue.JobHolder.safeRun(JobHolder.java:60)
         at com.path.android.jobqueue.executor.JobConsumerExecutor$JobConsumer.run(JobConsumerExecutor.java:201)
         at java.lang.Thread.run(Thread.java:818)

The returned result from server is :

{"data":{"user_id":"48","nickname":null,"password":null,"status":null},"status":1,"msg":"OK"}

This is correct json format, I don't understand why I get such exception?

Here us my interface:

public class ApiResult<T> {
    public T data;
    public int status;
    public String msg;
}

public interface ApiUsers {
    @POST("/users/new")
    public Call<ApiResult<User>> createUser(@Body User user);
}

public class User {
    public int user_id;
    public String registration;
    public int registration_type;
    public String avatar;
    public String nickname;
    public String password;
    public String status;

}

public class Api {

    // TODO modify the value
    public static final String BASE_URL = "xxx";

    private static Api instance = new Api();

    public static Api getInstance() {
        return instance;
    }

    private Api(){}

    public Retrofit getRetrofit() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .retryOnConnectionFailure(true)
                .connectTimeout(15, TimeUnit.SECONDS)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        return retrofit;
    }

    public <S> S createService(Class<S> serviceClass) {
        return getRetrofit().create(serviceClass);
    }
}

The caller code is:

ApiUsers api = Api.getInstance().createService(ApiUsers.class);
Call<ApiResult<User>> call = api.createUser(user);
CreateUserMessage message = new CreateUserMessage();
callNet(call, message);

Could anyone give any clue?

seaguest
  • 2,510
  • 5
  • 27
  • 45
  • Some characters such as NUL `\0` could also cause this and we can't see this character in debug. Try using Lenient mode. – Rohit5k2 Mar 14 '16 at 10:41
  • Also add the code where you are initializing retorofit i.e. your `Api.getInstance()` and the `User` class – Vedant Agarwala Mar 14 '16 at 10:55
  • You should see http://stackoverflow.com/a/11488385/2936153 – Rohit5k2 Mar 14 '16 at 11:28
  • @vedant1811, unfortunately, I don't find the tutorial for writing a custom gson converter, please check here https://futurestud.io/blog/retrofit-replace-the-integrated-json-converter, it is not posted yet. – seaguest Mar 14 '16 at 11:42
  • user_id get in string from webservice and your interface convert Integer. Please check it. – Kaushal Patel Mar 14 '16 at 18:59

3 Answers3

78

Finally I solved my problem which is not related to the json lenient mode, something wrong with my POST response (there some other non json output before the json data).

Here is the response from JakeWharton regarding how to set Gson lenient mode:

make sure that you have:compile 'com.google.code.gson:gson:2.6.1'

Gson gson = new GsonBuilder()
        .setLenient()
        .create();

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(client)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build();
TooCool
  • 10,598
  • 15
  • 60
  • 85
seaguest
  • 2,510
  • 5
  • 27
  • 45
  • Not working, as my response in XML data, i tried all possible ways – Prasad Mar 06 '17 at 12:04
  • 3
    I'm still getting the same error after implementing this solution. Can you please give me any pointers to fix this error? I'm using retrofit 2 and dealing with JSON and not XML – balajiprasadb Mar 20 '17 at 14:15
  • though I did not try but can help to someone. Try [**this**](https://stackoverflow.com/a/40013869/2624806). – CoDe Nov 03 '17 at 11:22
  • Oh God bless for this, I didn't know that var_dump affects results to server – NightStorm Jun 30 '22 at 02:27
5

I solved the problem

Gson gson = new GsonBuilder().setLenient().create();

OkHttpClient client = new OkHttpClient();

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("http://kafe.netai.net/")
    .client(client)
    .addConverterFactory(GsonConverterFactory.create(gson))
    .build();



compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.google.code.gson:gson:2.7'
SerGon146
  • 3
  • 4
-1

I solved my problem by removing extra HTML text and other white spaces from my JSON file.