jackson gson

SXIAOYI 2020-09-16

class JsonUtils {

   

   private static final Gson GSON =

            new GsonBuilder().disableHtmlEscaping().serializeNulls().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

 

   public static String toJson(Object obj) {

        return GSON.toJson(obj)

   }

}

 

 

public class JsonSerializer {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    private JsonSerializer(){}

    static {
        objectMapper.configure(com.fasterxml.jackson.core.JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        //对于值位null的则不进行序列化
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.registerModule(new Jdk8Module().configureAbsentsAsNulls(true));
    }

    public static String toJson(Object x) {
        try {
            return objectMapper.writeValueAsString(x);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T fromJson(String json, Class<T> targetType) {
        try {
            return objectMapper.readValue(json, targetType);

 

相关推荐

ganyouxianjava / 0评论 2012-05-31