I have a JSON with this structure:
{
"firstProperty": true,
"thisIsAString": "hi",
"myList": [
{"myBool": true},
{"myBool": false, "otherfield": true}
]
}
The myList is a List<MyClass> in the target class.
This MyClass only has the myBool field which causes the first element of the array to properly deserialize but unfortunately deserializing the second element causes it to fail with the error message Unknown property 'myBool' for class my.package.MyClass at JSON path $.otherfield.
Is there any way to just ignore fields in the JSON that don't exist in the target class of the deserialization? Maybe it is because of nested objects?
I already tried to add a custom type adapter like seen here but it didn't even call the method (the target class is a record which is why i have to use the third party library com.github.Marcono1234:gson-record-type-adapter-factory to deserialize it)
CodePudding user response:
AFAIK, Gson will ignore unknown fields automatically while deserialization. So, I assume that you have already created these 2 classes which look like:
public class MyClass {
private Boolean myBool;
// getter, setter and toString
}
public class MyResult {
private Boolean firstProperty;
private String thisIsAString;
List<MyClass> myList;
// getter, setter and toString
}
Then you can serialize your JSON string as follows:
String yourJsonStr = ""
"{\n"
" \"firstProperty\": true,\n"
" \"thisIsAString\": \"hi\",\n"
" \"myList\": [\n"
" {\"myBool\": true},\n"
" {\"myBool\": false, \"otherfield\": true}\n"
" ]\n"
"}";
Gson gson = new Gson();
MyResult myResult = gson.fromJson(yourJsonStr, MyResult.class);
System.out.println(myResult.toString());
Console output:
MyResult{firstProperty=true, thisIsAString='hi', myList=[MyClass{myBool=true}, MyClass{myBool=false}]}
CodePudding user response:
I found the issue, the third party library I use to deserialize into records has a TypeAdapterFactory which has a option to ignore unknown properties which is set to false per default.
Turning this option on produces the expected output.
