Using Jackson Library
- To work with Jackson, we need to add the Jackson Maven dependency in
pom.xml
file:
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
- Next, we need to serialize and deserialize objects to JSON string using
ObjectMapper
class as follows:
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonLab {
public static void main(String[] args) throws IOException {
ObjectMapper objMapper = new ObjectMapper();
ClassA classAObj = new ClassA("Demo", 20.0);
// Serialization
String jsonString = objMapper.writeValueAsString(classAObj);
System.out.println("Serialized String: " + jsonString);
// Deserialization
ClassA objFromStr = objMapper.readValue(jsonString, ClassA.class);
System.out.print("Deserialized Object: " + objFromStr.getField1() + " " + objFromStr.getField2());
}
}