1. 程式人生 > >java 利用 ObjectMapper 進行jsonString與物件互轉

java 利用 ObjectMapper 進行jsonString與物件互轉

先在專案內引入包。

gradle:

dependencies {
    compile(
            "com.fasterxml.jackson.core:jackson-databind:2.9.6"
    )
}

maven:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.6</version
>
</dependency>

建立類JsonUtil,將轉換方法寫成靜態,然後就可以在專案的任意地方都可以引用了。

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

public class JsonUtil {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    public static String parseJson
(Object o) { if (o == null) { return "null"; } try { return OBJECT_MAPPER.writeValueAsString(o); } catch (JsonProcessingException e) { e.printStackTrace(); } return "null"; } }