1

I am converting Java object to Json format to save them into the database. When I get these Jsons from the database, I need to convert them to Objects which they came from. To do this I am saving the objects' types and when I get the Jsons from the database I check their Object types with if clauses, but I think this is not the best way where there are a lof of objects. Is there a simplest way to do this?

Database table structure:

id | json_data | data_type
--------------------------
 1 | "{a:1 ..} | TypeA
--------------------------
 2 | so on.......

Java example to convert Jsons to Java objects:

ObjectMapper om = new ObjectMapper();
List<SpringEntityObject> allData = getAllDataFromDB();
for (SpringEntityObject o : allData) {
    if (o.getDataType().equals("TypeA")) {
        TypeA typeA = om.readValue(o.getJsonData(), TypeA.class);
        // there should be a simpler way to do this?
        ....
    } else if (o.getDataType().equals("TypeB")) {
        TypeB typeB = om.readValue(o.getJsonData(), TypeB.class);
        ....
    } ......
    else {....}
}
  • 2
    If you use JPA you will get it automatically – riorio Nov 03 '20 at 13:32
  • @riorio I use JPA but I can't make these objects' classes Serializable, they are autogenerated classes from wsdl file – oramakomaburamako Nov 03 '20 at 13:40
  • 1
    Look at Jackson's polymorphic deserialization: https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization It can be configured to deserialize to specific classes based on a property in your JSON. It can be difficult to grasp but there are numerous articles and examples online. – Paul Nov 03 '20 at 13:41
  • 1
    I believe you can make generated classes as well serializable by using JAXB bindings or whatever you are using . Have a look at this link here https://stackoverflow.com/questions/7009586/is-it-possible-to-generate-serializable-classes-with-cxf – Saurabh Chaturvedi Nov 03 '20 at 13:44

1 Answers1

3

The main issue you could have is that you need to change this block of code each time you add a new class.

You could store the full name (with namespace) of the class in the "data_type" column, and use Class.forName to dynamically obtain the class. This allows you to add classes without changing the deserialization code, which helps with maintenance.

for (SpringEntityObject o : allData) {
    Class clazz = Class.forName(o.getDataType());
    Object deserializedObject = om.readValue(o.getJsonData(), clazz);
}

Note that you will need to sync the class names in the database if you rename / move them (via a migration script).

Sherif Behna
  • 613
  • 5
  • 4