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.
classExcludeimplementsExclusionStrategy {
@OverridepublicbooleanshouldSkipClass(Class<?> arg0) {
// TODO Auto-generated method stubreturnfalse;
}
@OverridepublicbooleanshouldSkipField(FieldAttributes field) {
SerializedName ns = field.getAnnotation(SerializedName.class);
if(ns != null)
returnfalse;
returntrue;
}
}
Below is the class whose object you need to save/retrieve.
Add @SerializedName
for variables that needs to saved and/or retrieved.
classmyClass {
@SerializedName("id")intid;
@SerializedName("name")
String name;
}
Code to convert myObject to jsonString :
Excludeex=newExclude();
Gsongson=newGsonBuilder().addDeserializationExclusionStrategy(ex).addSerializationExclusionStrategy(ex).create();
StringjsonString= gson.toJson(myObject);
Code to get object from jsonString :
Excludeex=newExclude();
Gsongson=newGsonBuilder().addDeserializationExclusionStrategy(ex).addSerializationExclusionStrategy(ex).create();
myClassmyObject= 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:
publicclassAextendsB{
private BigDecimal netAmountTcy;
private BigDecimal netAmountPcy;
private BigDecimal priceTo;
privateString 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):
publicclassB {
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""