序列化操作(Gson ObjectMapper)


可以先閱讀
7. 物件的淺複製 深複製

眼睛比較好閱讀的JSON物件我們可以透過

public static Gson getPrettyGsonPretty(){
    return new GsonBuilder().setPrettyPrinting().create();
}

深複製(適用於單一物件)

public static Object cloneObject(Object o) {
        String s = gson.toJson(o);
        return gson.fromJson(s, o.getClass());
    }

深複製(單多物件)

public static Object deserializeFromObjectMapper(String json, Class<?> targetClass, boolean isCollection) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        if (isCollection) {
            JavaType clazzType = objectMapper.getTypeFactory().
                    constructCollectionType(List.class, targetClass);
            return objectMapper.readValue(json, clazzType);
        } else {
            return objectMapper.readValue(json, targetClass);
        }
    }
#java #JSON







你可能感興趣的文章

Geolocation based Speedometer and Compass

Geolocation based Speedometer and Compass

[BE101]  PHP 與 MySQL  (語法)

[BE101] PHP 與 MySQL (語法)

[ 筆記 ] Express 03 - Deployment

[ 筆記 ] Express 03 - Deployment






留言討論