Gson.toString() Gives Error "IllegalArgumentException: Multiple JSON Fields Named MPaint"
Solution 1:
According to my observation if you find multiple JSON fields for ANY_VARIABLE_NAME
, then it is likely that it is because GSON is not able to convert object to jsonString and jsonString to object. And you can try below code to solve it.
Add below class to to tell GSON to save and/or retrieve only those variables who have Serialized name declared.
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 is the class whose object you need to save/retrieve.
Add @SerializedName
for variables that needs to 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);
Code to get object from jsonString :
Exclude ex = new Exclude();
Gson gson = new GsonBuilder().addDeserializationExclusionStrategy(ex).addSerializationExclusionStrategy(ex).create();
myClass myObject = gson.fromJson(jsonString, myClass.class);
Solution 2:
It seems your problem is already solved but this is for people that didn't quite get their answer (like me):
A problem you can have is that the field already exists in a Class that you extend. In this case the field would already exist in Class B.
Say:
public class A extends B {
private BigDecimal netAmountTcy;
private BigDecimal netAmountPcy;
private BigDecimal priceTo;
private String segment;
private BigDecimal taxAmountTcy;
private BigDecimal taxAmountPcy;
private BigDecimal tradeFeesTcy;
private BigDecimal tradeFeesPcy;
// getter and setter for the above fields
}
where class B is something like (and maybe more duplicates of course):
public class B {
private BigDecimal netAmountPcy;
// getter and setter for the above fields
}
Just remove it the field "netAmountPcy" Class A and you will still have the field (because it extends the class).
Post a Comment for "Gson.toString() Gives Error "IllegalArgumentException: Multiple JSON Fields Named MPaint""