---
# System prepended metadata

title: '好用的Jackson , 做一個POJO 和 JSON轉換的JSONUtils'

---

# 好用的Jackson , 做一個POJO 和 JSON轉換的JSONUtils

Jackson是比較主流的基于Java的JSON類別庫，可用于Json和XML與JavaBean之間的序列化和反序列化，

沒看錯，Jackson也可以處理JavaBean與XML之間的轉換，基于jackson-dataformat-xml組件，而且比較JDK自帶XML實作更加高效和安全，而我們使用比較多的是處理JSON與JavaBean之間的功能，

Jackson主流到什么程度？單從Maven倉庫中的統計來看，Jackson的使用量排位第一，而Spring Boot支持的三個JSON庫（Gson、Jackson、JSON-B）中，Jackson是首選默認庫，

Jackson也有以下特點：依賴少，簡單易用，決議大Json速度快、記憶體占用比較低、擁有靈活的API、方便擴展與定制，

Jackson類別庫GitHub地址：https://github.com/FasterXML/jackson ，

Jackson的組成部分
Jackson的核心模塊由三部分組成（從Jackson 2.x開始）：jackson-core、jackson-annotations、jackson-databind，

jackson-core：核心包，定義了低級流（Streaming）API，提供基于"流模式"決議，Jackson內部實作正是通過高性能的流模式API的JsonGenerator和JsonParser來生成和決議json，
jackson-annotations，注解（Annotations）包，提供標準的Jackson注解功能；
jackson-databind：資料系結（Databind）包，實作了資料系結（和物件序列化）支持，它依賴于Streaming和Annotations包，提供基于“物件系結”決議的API（ObjectMapper）和"樹模型"決議的API（JsonNode）；基于"物件系結"決議的API和"樹模型"決議的API依賴基于“流模式”決議的API，
下面看一下不同環境下相關組件的依賴引入情況，

在SpringBoot當中，spring-boot-starter-web間接引入了Jackson組件，也就是如果你使用了SpringBoot框架，那么你的專案中已經有了Jackson依賴，下面的依賴省略了version和scope項

```
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
```

[參考網站](https://www.uj5u.com/qita/263396.html)

萬用的JSONUtils
```java=\
package com.camiol.utils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;


public class JSONUtils {
    private static final Logger log = LogManager.getLogger(JSONUtils.class);

    /**
     * 將物件轉成JSon String
     * @param value
     * @return
     */
    public static String toJSONString(Object value)
    {
        try
        {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.writeValueAsString(value);
        }
        catch (JsonProcessingException e)
        {
            log.info("toJSONString fail, Object=" + value, e);
            return null;
        }
    }

    /**
     * 將JSon String轉成物件
     * @param jsonString
     * @param object
     * @return
     */
    public static <T> T fromJSONString(String jsonString, Class<T> object)
    {
        if (jsonString == null || object == null)
        {
            log.warn("fromJSONString format error");
            return null;
        }

        try
        {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
            return mapper.readValue(jsonString, object);
        }
        catch (JsonProcessingException e)
        {
            log.info("fromJSONString fail, jsonString=" + jsonString + ", object=" + object, e);
            return null;
        }
    }

    /**
     * 將Map<String, Object>轉成JSon String
     *
     */
    public static String readMapToJSON(Map<String, Object> map)
    {
        if (map == null || map.isEmpty() )
        {
            log.warn("readMaptoJSON format error");
            return null;
        }

        try
        {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.writeValueAsString(map);
        }
        catch (JsonProcessingException e)
        {
            log.info("readMaptoJSON fail, map= " + map, e);
            return null;
        }
    }
    
    /**
     * 將JSon String轉成Map<String, Object>
     * 
     */
    public static Map<String, Object> readJSONtoMap(String jsonString)
    {
        if (jsonString == null || jsonString.trim().length() == 0)
        {
            log.warn("readJSONtoMap format error");
            return null;
        }

        try
        {
            ObjectMapper mapper = new ObjectMapper();
            TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>(){};
            return mapper.readValue(jsonString, typeRef);
        }
        catch (JsonProcessingException e)
        {
            log.info("readJSONtoMap fail, jsonString=" + jsonString, e);
            return null;
        }
    }
    
    
    /**
     * 將List<Object>轉成JSon String
     * 
     */
    public static String readListToJSON(List<Object> list)
    {
        if (list == null || list.isEmpty() )
        {
            log.warn("readListToJSON format error");
            return null;
        }

        try
        {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.writeValueAsString(list);
        }
        catch (JsonProcessingException e)
        {
            log.info("readListToJSON fail, list=" + list, e);
            return null;
        }
    }
    
    /**
     * 將JSon String轉成 List<Object>
     * 
     */
    public static List< Object> readJSONtoList(String jsonString)
    {
        if (jsonString == null || jsonString.trim().length() == 0)
        {
            log.warn("readJSONtoList format error");
            return null;
        }

        try
        {
            ObjectMapper mapper = new ObjectMapper();
            TypeReference<List< Object>> typeRef = new TypeReference<List< Object>>(){};
            return mapper.readValue(jsonString, typeRef);
        }
        catch (JsonProcessingException e)
        {
            log.info("readJSONtoList fail, jsonString=" + jsonString, e);
            return null;
        }
    }
     
}

```

使用的時候，可以自由的將map組成JSON字串，或將JSON字串轉成POJO

以下是練習:
```java=\
 public static void main(String[] args) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        
        map.put("date", "20220722");
        map.put("revers", "false");
        
        HashMap<String, Object> details = new HashMap<String, Object>();
        details.put("assetId", "khr#nbc");
        details.put("currency", "KHR");

        HashMap<String, Object> sourceOfFunds = new HashMap<String, Object>();
        sourceOfFunds.put("phoneNumber", "0975123456");
        sourceOfFunds.put("name", null);
        details.put("sourceOfFunds", sourceOfFunds);
        
        map.put("details",details);
        
        String json = JSONUtils.readMapToJSON(map);
        System.out.println(json);
        
        TransactionContent content = JSONUtils.fromJSONString(json, TransactionContent.class);
        
        System.out.println(content);
        
    }
```

把JSON轉出來的List<Object>轉成自己要的POJO
```java=\
List<Bank> resultList = new ArrayList<>();
List<Object> jList = JSONUtils.readJSONtoList(respBody);

if(jList != null && !jList.isEmpty()) {
    for(Object obj : jList) {
        Bank b = JSONUtils.fromJSONString(JSONUtils.toJSONString(obj), Bank.class);

        resultList.add(b);
    }
}
```



###### tags: java