Zidane Zidane - 5 months ago 156
JSON Question

How to solve retrofit Conversion Exception when converting to json string

I am trying to post a set of parameters to api and I am getting an error that I do not quite understand

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


I am suspecting three areas that might be causing this error


  1. I have either declared that last parameter incorrectly

    @Query("AppTimes") String appTimes

  2. My Gson conversion result is not correct and perhaps I should use another converter

  3. It is not possible to convert a java list to json



This is what my rest adapter looks like

public static DigitechService createService(Context context)
{
Gson gson = new GsonBuilder()
//.setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'")
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss") // 2015-02-23T00:00:00
.create();

// Only allow LogLevel for Debug
RestAdapter restAdapter = new RestAdapter.Builder()
.setLogLevel(Globals.TEST == false ? RestAdapter.LogLevel.NONE : RestAdapter.LogLevel.FULL)
.setEndpoint(Globals.digitechApiBaseUrl)
.setConverter(new GsonConverter(gson))
.setRequestInterceptor(new AuthRequestInterceptor(context))
.build();

return restAdapter.create(DigitechService.class);
}


This is my interface

@POST("/api/v1/LoadAppTimeUsage/")
void loadAppTimeUsage(
@Query("cellPhoneNumber") String cellPhoneNumber,
@Query("appName") String appName,
@Query("timeSpent") int timeSpent,
@Query("AppTimes") String appTimes,
Callback<List<ResultPost>> cb
);


My post method

public List<AppTimeUsage> postAppTimeUsage(List<AppTimeUsage> atu)
{
String json = new Gson().toJson(atu);
TinyDB settings = new TinyDB(mContext);
// Show progress
final ProgressDialog progress = new ProgressDialog(mContext);
progress.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {

}
});
progress.show();


String cellphoneNumber = settings.getString(AppPreferences.CONFIRMED_CellPhoneNUmber);


DigiTechClient.createService(mContext).loadAppTimeUsage(cellphoneNumber, appName ,timeSpent, json, new Callback<List<ResultPost>>() {
@Override
public void success(List<ResultPost> resultPosts, Response response) {
if (progress != null) progress.dismiss();
}

@Override
public void failure(RetrofitError error) {
if (progress != null) progress.dismiss();

DeviceApp.handleError(error);

if (error.getResponse() != null) {
RestError err = (RestError) error.getBodyAs(RestError.class);

Toast.makeText(mContext, err.Message, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(mContext, error.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
return atu;
}


My StackTrace

java.lang.RuntimeException: retrofit.converter.ConversionException: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
at com.xera.deviceinsight.structs.AppTimeUsageRecorder$2.failure(AppTimeUsageRecorder.java:163)
at retrofit.CallbackRunnable$2.run(CallbackRunnable.java:53)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
Caused by: retrofit.converter.ConversionException: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
at retrofit.converter.GsonConverter.fromBody(GsonConverter.java:67)
at retrofit.RetrofitError.getBodyAs(RetrofitError.java:137)
at com.xera.deviceinsight.structs.AppTimeUsageRecorder$2.failure(AppTimeUsageRecorder.java:163)
at retrofit.CallbackRunnable$2.run(CallbackRunnable.java:53)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:200)
at com.google.gson.Gson.fromJson(Gson.java:810)
at com.google.gson.Gson.fromJson(Gson.java:775)
at retrofit.converter.GsonConverter.fromBody(GsonConverter.java:63)
at retrofit.RetrofitError.getBodyAs(RetrofitError.java:137)
at com.xera.deviceinsight.structs.AppTimeUsageRecorder$2.failure(AppTimeUsageRecorder.java:163)
at retrofit.CallbackRunnable$2.run(CallbackRunnable.java:53)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:387)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:189)
at com.google.gson.Gson.fromJson(Gson.java:810)
at com.google.gson.Gson.fromJson(Gson.java:775)
at retrofit.converter.GsonConverter.fromBody(GsonConverter.java:63)
at retrofit.RetrofitError.getBodyAs(RetrofitError.java:137)
at com.xera.deviceinsight.structs.AppTimeUsageRecorder$2.failure(AppTimeUsageRecorder.java:163)
at retrofit.CallbackRunnable$2.run(CallbackRunnable.java:53)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)

Answer

Don't convert the parameter to a JSON string. Instead, send the list object as a body parameter and it will automatically be converted to JSON.

As an example:

@POST("/api/v1/LoadAppTimeUsage/")
void loadAppTimeUsage(
        @Body List<MyApp> appTimes,
        Callback<List<ResultPost>> cb
);
Comments