Java 对象 、String 、JSON 互转

一、引入依赖

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20190722</version>
        </dependency>
        
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>RELEASE</version>
        </dependency>

二、代码
1、Object => JSON String

    public static String ObjectToJSONString(Object obj) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setPrettyPrinting();
        Gson gson = gsonBuilder.create();
        return gson.toJson(obj);
    }
    

2、JSON String 转 Object

    public static <T> T fromJsonObject(String json, Class<T> clazz) {
        JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
        return new Gson().fromJson(jsonObject, clazz);
    }

你可能感兴趣的:(工具类使用)