Java Object to Json toJson(Object object)

Here you can find the source of toJson(Object object)

Description

Converts object to JSON string

License

Apache License

Parameter

Parameter Description
object to be converted

Return

JSON representation of object

Declaration

public static String toJson(Object object) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import com.fasterxml.jackson.core.JsonProcessingException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
    private static final ThreadLocal<ObjectMapper> tlObjectMapper = new ThreadLocal<ObjectMapper>() {
        @Override/*from   w  w w . j  av a  2s .  c  o m*/
        protected ObjectMapper initialValue() {

            return new ObjectMapper();
        }
    };

    /**
     * Converts object to JSON string
     *
     * @param object to be converted
     * @return JSON representation of object
     */
    public static String toJson(Object object) {

        try {
            return getObjectMapper().writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException(
                    "Given Object could not be serialized to JSON. Error: " + e.getMessage());
        }
    }

    /**
     * Allows JSON serialization with custom mapping
     *
     * @param object       to be serialized
     * @param customMapper custom mapper
     * @return JSON representation of object
     */
    public static String toJson(Object object, ObjectMapper customMapper) {

        if (customMapper == null) {
            throw new IllegalArgumentException("Missing custom mapper!");
        }

        try {
            return customMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException(
                    "Given Object could not be serialized to JSON. Error: " + e.getMessage());
        }
    }

    /**
     * Returns a thread-local instance of JSON ObjectMapper.
     *
     * @return ObjectMapper.
     */
    public static ObjectMapper getObjectMapper() {

        return tlObjectMapper.get();
    }
}

Related

  1. toJson(Object o)
  2. toJSON(Object obj)
  3. toJSON(Object obj)
  4. toJson(Object obj)
  5. toJson(Object object)
  6. toJson(Object object)
  7. toJson(Object value)
  8. toJSON(T obj)
  9. toJSON(T obj)