Let's say I have simple class:
public class TestClass
{
public String field1 = "Field1";
public String field2 = "Field2";
public String field3 = "Field3";
}
I have multiple pojo classes in my project and I want to be able to serialize each object to json. So I created new Serializer
class (gson used to serialize):
public class Serializer
{
public String toJson()
{
return new Gson().toJson(this);
}
}
And my example class extends Serializer
:
public class TestClass extends Serializer
{
public String field1 = "Field1";
public String field2 = "Field2";
public String field3 = "Field3";
}
And I am able to serialize any object of class extending Serializer
by calling toJson
method, like this:
TestClass test1 = new TestClass();
String json = test1.toJson();
Now I want construct class object by calling static method fromJson
. So my TestClass
looks like this:
public class TestClass extends Serializer
{
public String field1 = "Field1";
public String field2 = "Field2";
public String field3 = "Field3";
public static TestClass fromJson(String json)
{
return new Gson().fromJson(json, new TypeToken<TestClass>() {}.getType());
}
}
So, I can create new object by calling:
TestClass test2 = TestClass.fromJson(json);
Of course, this is not good approach, because I need to include fromJson
implementation in my all classes.
Question: how to move fromJson
to superclass (Serializer
), and provide single, type dependent implementation for fromJson
method?
You can define static fromJson()
method in Serializer
base class:
public static class Serializer {
public static <T> T fromJson(String json, Type type) {
return new Gson().fromJson(json, type);
}
}
And use it as:
TestClass obj = TestClass.fromJson(json, TestClass.class);
It's not perfect with redundant type information and doesn't support generics well. One should favor composition over inheritance and in this case keep serialization out of the class hierarchy. This approach has no advantage over simply:
TestClass obj = new Gson().fromJson(json, TestClass.class);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With