JSON-Object Serialization and Deserialization in Java


Often, we need to be able to convert Object to JSON (which is also called persistence of data) and then be able to convert it (JSON) back to Object. We can use the ObjectMapper in Java to achieve this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.helloacm.com
 
import com.fasterxml.jackson.databind.ObjectMapper;
 
public class JsonUtil {
 
  public static final <T> T convertJsonToObject(String jsonString, Class<T> clazz) {
    if (!StringUtils.isEmpty(jsonString) && clazz != null) {
      try {
        var om = new ObjectMapper();
        return om.readValue(jsonString, clazz);
      } catch (Exception ex) {
        // rethrow as Runtime Exception
        throw new RuntimeException(ex);
      }
    } else {
      return null;
    }
  }
 
  public static final String convertObjectToJson(Object obj) {
    if (obj == null) {
      return null;
    } 
    var om = new ObjectMapper();
    try {
      return om.writeValueAsString(obj);
    } catch (Exception ex) {
      // rethrow as Runtime Exception
      throw new RuntimeException(ex);
    }
  }
}
package com.helloacm.com

import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {

  public static final <T> T convertJsonToObject(String jsonString, Class<T> clazz) {
    if (!StringUtils.isEmpty(jsonString) && clazz != null) {
      try {
        var om = new ObjectMapper();
        return om.readValue(jsonString, clazz);
      } catch (Exception ex) {
        // rethrow as Runtime Exception
        throw new RuntimeException(ex);
      }
    } else {
      return null;
    }
  }

  public static final String convertObjectToJson(Object obj) {
    if (obj == null) {
      return null;
    } 
    var om = new ObjectMapper();
    try {
      return om.writeValueAsString(obj);
    } catch (Exception ex) {
      // rethrow as Runtime Exception
      throw new RuntimeException(ex);
    }
  }
}

If there are conversion errors, a Runtime Exception will be re-thrown.

Example Usage:

1
2
3
var object = new Object();
var json = JsonUtil.convertObjectToJson(object);
var decodedObject = JsonUtil.convertJsonToObject(json);
var object = new Object();
var json = JsonUtil.convertObjectToJson(object);
var decodedObject = JsonUtil.convertJsonToObject(json);

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
232 words
Last Post: Teaching Kids Programming - Binary Matrix Leftmost One
Next Post: Teaching Kids Programming - Beer Bottle Exchange Algorithm via Simulation

The Permanent URL is: JSON-Object Serialization and Deserialization in Java

Leave a Reply