Java – Gson.toString() gives error “IllegalArgumentException: multiple JSON fields named mPaint”

Gson.toString() gives error “IllegalArgumentException: multiple JSON fields named mPaint”… here is a solution to the problem.

Gson.toString() gives error “IllegalArgumentException: multiple JSON fields named mPaint”

I want to convert a custom object to a string and save it in SharePreferences, which is my ultimate goal. I tried the following line that failed.

String matchString = gson.toJson(userMatches);

Log:

10-11 15:24:33.245: E/AndroidRuntime(21427): FATAL EXCEPTION: main
10-11 15:24:33.245: E/AndroidRuntime(21427): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=4001, result=-1, data=null}
                                             to activity {com.objectlounge.ridesharebuddy/com.objectlounge.ridesharebuddy.activities.RS_CreateTripActivity}:
                                             java.lang.IllegalArgumentException: class android.text.BoringLayout declares multiple JSON fields named mPaint
10-11 15:24:33.245: E/AndroidRuntime(21427): at android.app.ActivityThread.deliverResults(ActivityThread.java:3302)

I tried a lot of options and believed in something with variables in custom objects. The object to note in the error log is java.lang.IllegalArgumentException: class android.text.BoringLayout declares multiple JSON fields named mPaint. Not sure what mPaint is.

Does anyone know?

Solution

From my observations, if you find that ANY_VARIABLE_NAME has multiple JSON fields, it’s most likely because GSON can’t convert objects to jsonString and jsonString to objects. You can try the code below to solve it.

Add the following class to tell GSON to save and/or retrieve only those variables that declare serialized names.

class Exclude implements ExclusionStrategy {

@Override
    public boolean shouldSkipClass(Class<?> arg0) {
         TODO Auto-generated method stub
        return false;
    }

@Override
    public boolean shouldSkipField(FieldAttributes field) {
        SerializedName ns = field.getAnnotation(SerializedName.class);
        if(ns != null)
            return false;
        return true;
    }
}

Below are the classes whose objects you need to save/retrieve.
Add @SerializedName for variables that need to be saved and/or retrieved.

class myClass {
    @SerializedName("id")
    int id;
    @SerializedName("name")
    String name;
}

Code to convert myObject to jsonString:

Exclude ex = new Exclude();
    Gson gson = new GsonBuilder().addDeserializationExclusionStrategy(ex).addSerializationExclusionStrategy(ex).create();
String jsonString = gson.toJson(myObject);

Get the code for the object from jsonString:

Exclude ex = new Exclude();
Gson gson = new GsonBuilder().addDeserializationExclusionStrategy(ex).addSerializationExclusionStrategy(ex).create();
myClass myObject = gson.fromJson(jsonString, myClass.class);

Related Problems and Solutions