Hot questions for Handling MalformedJsonException in Retrofit

Top 10 Java Open Source / Retrofit / Handling MalformedJsonException

Retrofit2.0 gets MalformedJsonException while the json seems correct?

Question: 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: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $
         at retrofit2.converter.gson.GsonResponseBodyConverter.convert(
         at retrofit2.converter.gson.GsonResponseBodyConverter.convert(
         at retrofit2.OkHttpCall.parseResponse(
         at retrofit2.OkHttpCall.execute(
         at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(

The returned result from server is :


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

Here is my interface:

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

public interface ApiUsers {
    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();
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)

        Retrofit retrofit = new Retrofit.Builder()

        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?

Answer: there is something wrong with your 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 ''

Gson gson = new GsonBuilder()

Retrofit retrofit = new Retrofit.Builder()

MalformedJsonException with Retrofit API?

Question: I need send a json to my webservice, json is:

    "Sala": {
        "usuario": "%@",
        "adversario": "%@",
        "atualizacao": "%@",
        "device": "%@",
        "device_tipo": "ios"

I'm trying do it using Retrofit API 1.8. When I try send the post throws an exception. Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 7 path $

I'm trying this

public class ChatObject {
    private String usuario;
    private String adversario;
    private String atualizacao;
    private String email;
    private String device;
    private String device_tipo;

Retrofit Interface

    public void onReceiveMessage(@Body ChatObject obj,
                                 Callback<JsonElement> response);


public void receiveMessage(){
    ChatObject chatObject = new ChatObject(BatalhaConfigs.USUARIO_EMAIL,
                                           new Date().toString(),

    RestAdapter adapter = new RestAdapter.Builder()
            .setRequestInterceptor(new CustomRequestInterceptor())
    ChatListener listener = adapter.create(ChatListener.class);
    listener.onReceiveMessage(chatObject, new Callback<JsonElement>() {
        public void success(JsonElement jsonElement, retrofit.client.Response response) {
            Log.i("JSON ELEMENT->", jsonElement.toString());

        public void failure(RetrofitError error) {
            Log.i("FALHOU->", error.getLocalizedMessage());


Answer: " Use JsonReader.setLenient(true)" is usually thrown when there is some character(s) that malforms the JSON. Exception message itself suggest to make the deserialization more tolerant.

But I suggest you to fix your JSON and trim it from unwanted characters.

You should extend GsonConverter and override fromBody() to make Gson read from the tolerant JsonReader. Then just set it to your RestAdapter. This will attempt to use tolerant JsonReader to deserialize and then close it, if not exception is thrown.

public class LenientGsonConverter extends GsonConverter {
private Gson mGson;

public LenientGsonConverter(Gson gson) {
    mGson = gson;

public LenientGsonConverter(Gson gson, String charset) {
    super(gson, charset);
    mGson = gson;

public Object fromBody(TypedInput body, Type type) throws ConversionException {
    boolean willCloseStream = false; // try to close the stream, if there is no exception thrown using tolerant  JsonReader
    try {
        JsonReader jsonReader = new JsonReader(new InputStreamReader(;
        Object o = mGson.fromJson(jsonReader,type);
        willCloseStream = true;
        return o;
    } catch (IOException e) {
    }finally {
        if(willCloseStream) {

    return super.fromBody(body, type);

private void closeStream(TypedInput body){
        try {
            InputStream in =;
        } catch (IOException e) {