jmu.edu.cn.util.JsonMapper.java Source code

Java tutorial

Introduction

Here is the source code for jmu.edu.cn.util.JsonMapper.java

Source

/**
 * Copyright (c) 2005-2012 springside.org.cn
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 */

package jmu.edu.cn.util;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;

/**
 * ??JacksonJSON String<->Java ObjectMapper.
 * <p/>
 * ???, ??builder.
 *
 * @author calvin
 */
public class JsonMapper {

    private static Logger loGGER = LoggerFactory.getLogger(JsonMapper.class);

    private ObjectMapper mapper;

    public JsonMapper() {
        this(null);
    }

    public JsonMapper(Include include) {
        mapper = new ObjectMapper();
        // ?
        if (include != null) {
            mapper.setSerializationInclusion(include);
        }
        // JSONJava
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }

    /**
     * ??Null?Empty(List.isEmpty)JsonMapper,?.
     */
    public static JsonMapper nonEmptyMapper() {
        return new JsonMapper(Include.NON_EMPTY);
    }

    /**
     * ???JsonMapper, ??
     */
    public static JsonMapper nonDefaultMapper() {
        return new JsonMapper(Include.NON_DEFAULT);
    }

    /**
     * Object?POJO?Collection Null, "null". ??, "[]".
     */
    public String toJson(Object object) {

        try {
            return mapper.writeValueAsString(object);
        } catch (IOException e) {
            loGGER.warn("write to json string error:" + object, e);
            return null;
        }
    }

    /**
     * ???POJO?CollectionList<String>.
     * <p/>
     * JSONNull"null", Null. JSON"[]", ?.
     * <p/>
     * ?????CollectionList<MyBean>, fromJson(String, JavaType)
     *
     * @see #fromJson(String, JavaType)
     */
    public <T> T fromJson(String jsonString, Class<T> clazz) {
        if (StringUtils.isEmpty(jsonString)) {
            return null;
        }

        try {
            return mapper.readValue(jsonString, clazz);
        } catch (IOException e) {
            loGGER.warn("parse json string error:" + jsonString, e);
            return null;
        }
    }

    /**
     * ?????CollectionList<Bean>,
     * createCollectionType()contructMapType(), ?.
     */
    public <T> T fromJson(String jsonString, JavaType javaType) {
        if (StringUtils.isEmpty(jsonString)) {
            return null;
        }

        try {
            return (T) mapper.readValue(jsonString, javaType);
        } catch (IOException e) {
            loGGER.warn("parse json string error:" + jsonString, e);
            return null;
        }
    }

    public <T> T fromJson(HttpServletRequest request, Class<T> pojoClass) throws IOException {
        ServletInputStream inputStream = request.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        byte[] buf = new byte[1024];
        int index = inputStream.read(buf);
        while (index > 0) {
            baos.write(buf, 0, index);
            index = inputStream.read(buf);
        }
        return mapper.readValue(baos.toByteArray(), pojoClass);
    }

    /**
     * Collection.
     */
    public JavaType contructCollectionType(Class<? extends Collection> collectionClass, Class<?> elementClass) {
        return mapper.getTypeFactory().constructCollectionType(collectionClass, elementClass);
    }

    /**
     * Map.
     */
    public JavaType contructMapType(Class<? extends Map> mapClass, Class<?> keyClass, Class<?> valueClass) {
        return mapper.getTypeFactory().constructMapType(mapClass, keyClass, valueClass);
    }

    /**
     * JSON??BeanBean?.
     */
    public void update(String jsonString, Object object) {
        try {
            mapper.readerForUpdating(object).readValue(jsonString);
        } catch (JsonProcessingException e) {
            loGGER.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
        } catch (IOException e) {
            loGGER.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
        }
    }

    /**
     * JSONP?.
     */
    public String toJsonP(String functionName, Object object) {
        return toJson(new JSONPObject(functionName, object));
    }

    /**
     * ?EnumtoStringEnum, FalseEnumname()Enum, ?False.
     * ??Mapper, ?.
     */
    public void enableEnumUseToString() {
        mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
        mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
    }

    /**
     * ?JaxbAnnotationPOJOannotation?Jackson?
     * jaxbannotation??jackson
     */
    public void enableJaxbAnnotation() {
        JaxbAnnotationModule module = new JaxbAnnotationModule();
        mapper.registerModule(module);
    }

    /**
     * ?Mapper??API.
     */
    public ObjectMapper getMapper() {
        return mapper;
    }
}