---
title: "jackson gson"
author: "yangbinfx"
date: "2020-09-16T15:22:47Z"
tags: []
categories: ["移动开发"]
slug: "jackson-gson"
draft: false
lastmod: "2020-09-16T15:24:29Z"
id: 2516795
url: "https://yangbinfx.iteye.com/blog/2516795"
---

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);
```