All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.xiongyingqi.common.utils.JacksonHelper Maven / Gradle / Ivy

The newest version!
package com.xiongyingqi.common.utils;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

/**
 * @author xiongyingqi
 * @since 16-6-8 下午5:34
 */
public abstract class JacksonHelper {
  private static final ObjectMapper mapper = newMapper();

  public static String getJsonString(Object o) {
    ObjectMapper mapper = newMapper();
    try {
      return mapper.writeValueAsString(o);
    } catch (JsonProcessingException e) {
      return null;
    }
  }

  public static  T convertJsonByClass(String json, Class clazz) throws IOException {
    ObjectMapper mapper = newMapper();
    return mapper.readValue(json, clazz);
  }


  public static ObjectMapper newConfiguredMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
    return objectMapper;
  }

  public static ObjectMapper newMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
    return objectMapper;
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy