Convert Object to JSON and JSON to Object with FasterXML/jackson-databind

Refer the FasterXml/Jackson-bind API from the below GitHub repo. This is very helpful for handling the various data format especially JSON

https://github.com/FasterXML/jackson-databind

The sample code to convert Object to JSON and JSON to Object is given below,

Maven Dependencies,


 <dependency>
            <groupId>com.fasterxml.jackson.jr</groupId>
            <artifactId>jackson-jr-objects</artifactId>
            <version>2.5.0</version>
 </dependency>
 <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.0</version>
    </dependency>

Code:


import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class JSONUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(JSONUtils.class);

    public static void main(String[] args) throws IOException {

        LOGGER.info("Converting Object to String");
        Customer customer = new Customer();
        customer.setCustomerId("cust1234");
        customer.setFirstName("Bala");
        customer.setLastName("samy");
        String objectString = convertObjectAsString(customer);
        LOGGER.info("Converting String:{}", objectString);

        LOGGER.info("Converting String to Customer Object");
        Customer customer1 = convertJsonStringAsObject(objectString);
        LOGGER.info("Converted Object:{}", customer1);

    }

    public static String convertObjectAsString(Object obj) throws JsonProcessingException {
        String content = null;
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
            content = mapper.writeValueAsString(obj);
        } catch (Exception e) {
            LOGGER.error("Exception happened while doing the conversion", e);
            throw e;
        }
        return content;
    }

    public static Customer convertJsonStringAsObject(String content) throws IOException {

        Customer customer = null;
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
            customer = mapper.readValue(content, Customer.class);
        } catch (Exception e) {
            LOGGER.error("Exception happened while doing the conversion", e);
            throw e;
        }
        return customer;
    }


    public static class Customer {

        private String firstName;
        private String lastName;
        private String customerId;

        public String getFirstName() {
            return firstName;
        }

        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }

        public String getLastName() {
            return lastName;
        }

        public void setLastName(String lastName) {
            this.lastName = lastName;
        }

        public String getCustomerId() {
            return customerId;
        }

        public void setCustomerId(String customerId) {
            this.customerId = customerId;
        }

        @Override

        public boolean equals(Object o) {
            if (this == o) return true;

            if (o == null || getClass() != o.getClass()) return false;

            Customer customer = (Customer) o;

            return new EqualsBuilder()
                    .append(firstName, customer.firstName)
                    .append(lastName, customer.lastName)
                    .append(customerId, customer.customerId)
                    .isEquals();
        }

        @Override
        public int hashCode() {
            return new HashCodeBuilder(17, 37)
                    .append(firstName)
                    .append(lastName)
                    .append(customerId)
                    .toHashCode();
        }

        @Override
        public String toString() {
            return new ToStringBuilder(this)
                    .append("firstName", firstName)
                    .append("lastName", lastName)
                    .append("customerId", customerId)
                    .toString();
        }
    }

}

Output:


Converting Object to String
Converting String:{"firstName":"Bala","lastName":"samy","customerId":"cust1234"}
Converting String to Customer Object
Converted Object:JSONUtils$Customer@130f889[firstName=Bala,lastName=samy,customerId=cust1234]

Convert Object as Json using FasterXML/jackson-jr

Its an alternative to jackson-bind API for processing JSON. It provides an easy way to convert the java object to json and vice versa.

This API can be used, when the size of the third party jar and startup time matters in your application. This API has very low initialization overhead compared to jackson-bind

The Github repository is https://github.com/FasterXML/jackson-jr

pom.xml


<dependency>
  <groupId>com.fasterxml.jackson.jr</groupId>
  <artifactId>jackson-jr-objects</artifactId>
  <version>2.8.5</version>
</dependency>

Sample code to convert the Object to json is given below,
JSONUtils:


import com.fasterxml.jackson.jr.ob.JSON;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class JSONUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(JSONUtils.class);

    public static void main(String[] args) throws IOException {

        LOGGER.info("Converting Object to String");
        Customer customer = new Customer();
        customer.setCustomerId("cust1234");
        customer.setFirstName("Bala");
        customer.setLastName("samy");
        String objectString = convertObjectAsString(customer);
        LOGGER.info("Converting String:{}", objectString);

        LOGGER.info("Converting String to Customer Object");
        Customer customer1 = convertJsonStringAsObject(objectString);
        LOGGER.info("Converted Object:{}", customer1);

    }

    public static String convertObjectAsString(Object obj) throws IOException {
        return JSON.std.asString(obj);
    }

    public static Customer convertJsonStringAsObject(String content) throws IOException {
        return JSON.std.beanFrom(Customer.class, content);
    }


    public static class Customer {

        private String firstName;
        private String lastName;
        private String customerId;

        public String getFirstName() {
            return firstName;
        }

        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }

        public String getLastName() {
            return lastName;
        }

        public void setLastName(String lastName) {
            this.lastName = lastName;
        }

        public String getCustomerId() {
            return customerId;
        }

        public void setCustomerId(String customerId) {
            this.customerId = customerId;
        }

        @Override

        public boolean equals(Object o) {
            if (this == o) return true;

            if (o == null || getClass() != o.getClass()) return false;

            Customer customer = (Customer) o;

            return new EqualsBuilder()
                    .append(firstName, customer.firstName)
                    .append(lastName, customer.lastName)
                    .append(customerId, customer.customerId)
                    .isEquals();
        }

        @Override
        public int hashCode() {
            return new HashCodeBuilder(17, 37)
                    .append(firstName)
                    .append(lastName)
                    .append(customerId)
                    .toHashCode();
        }

        @Override
        public String toString() {
            return new ToStringBuilder(this)
                    .append("firstName", firstName)
                    .append("lastName", lastName)
                    .append("customerId", customerId)
                    .toString();
        }
    }

}

Output:


2016-12-29T11:44:54.319-0500 [main] INFO  o.c.o.m.JSONUtils - Converting Object to String
2016-12-29T11:44:54.398-0500 [main] INFO  o.c.o.m.JSONUtils - Converting String:{"customerId":"cust1234","firstName":"Bala","lastName":"samy"}
2016-12-29T11:44:54.399-0500 [main] INFO  o.c.o.m.JSONUtils - Converting String to Customer Object
2016-12-29T11:44:54.405-0500 [main] INFO  o.c.o.m.JSONUtils - Converted Object:org.cas.osd.mp.JSONUtils$Customer@31ef45e3[firstName=Bala,lastName=samy,customerId=cust1234]