Search code examples
javajsonobjectobjectmapper

What is the Best Way for Converting a Json to a Java Object with Using ObjectMapper?


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 {....}
}

Solution

  • 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).