I use gson 2.8.6 and this is my code:
interface Foo {
String getTest();
}
class FooImpl implements Foo {
private String test;
@Override
public String getTest() {
return this.test;
}
public void setTest(String test) {
this.test = test;
}
@Override
public String toString() {
return "FooImpl{" + "test=" + test + '}';
}
}
class Bar {
private Foo foo;
public Foo getFoo() {
return foo;
}
public void setFoo(Foo foo) {
this.foo = foo;
}
@Override
public String toString() {
return "Bar{" + "foo=" + foo + '}';
}
}
class FooInstanceCreator implements InstanceCreator<Foo> {
@Override
public Foo createInstance(Type type) {
return new FooImpl();
}
}
public class NewMain3 {
public static void main(String[] args) {
FooImpl foo = new FooImpl();
foo.setTest("this is test");
Bar bar = new Bar();
bar.setFoo(foo);
Gson gson = new GsonBuilder()
.serializeNulls()
.registerTypeAdapter(Foo.class, new FooInstanceCreator())
.create();
//TO
String to = gson.toJson(bar);
System.out.println("TO:" + to);
//FROM
Bar from = gson.fromJson(to, Bar.class);
System.out.println("FROM:" + from);
}
}
And this is output:
TO:{"foo":{"test":"this is test"}}
FROM:Bar{foo=FooImpl{test=null}}
As you see test
field is lost. Could anyone say how to fix it?