1. 程式人生 > >Json序列化工具類

Json序列化工具類

package com.mmall.util;

import com.google.common.collect.Lists;
import com.mmall.pojo.Category;
import com.mmall.pojo.TestPojo;
import com.mmall.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.codehaus.jackson.type.JavaType;
import org.codehaus.jackson.type.TypeReference;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhang
 */
@Slf4j
public class JsonUtil {

    private static ObjectMapper objectMapper = new ObjectMapper();
    static{
        //物件的所有欄位全部列入
        objectMapper.setSerializationInclusion(Inclusion.ALWAYS);

        //取消預設轉換timestamps形式
        objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,false);

        //忽略空Bean轉json的錯誤
        objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS,false);

        //所有的日期格式都統一為以下的樣式,即yyyy-MM-dd HH:mm:ss
        objectMapper.setDateFormat(new SimpleDateFormat(DateTimeUtil.STANDARD_FORMAT));

        //忽略 在json字串中存在,但是在java物件中不存在對應屬性的情況。防止錯誤
        objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);
    }



    public static <T> String obj2String(T obj){
        if(obj == null){
            return null;
        }
        try {
            return obj instanceof String ? (String)obj :  objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            log.warn("Parse Object to String error",e);
            return null;
        }
    }

    public static <T> String obj2StringPretty(T obj){
        if(obj == null){
            return null;
        }
        try {
            return obj instanceof String ? (String)obj :  objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        } catch (Exception e) {
            log.warn("Parse Object to String error",e);
            return null;
        }
    }

    public static <T> T string2Obj(String str,Class<T> clazz){
        if(StringUtils.isEmpty(str) || clazz == null){
            return null;
        }

        try {
            return clazz.equals(String.class)? (T)str : objectMapper.readValue(str,clazz);
        } catch (Exception e) {
            log.warn("Parse String to Object error",e);
            return null;
        }
    }

    public static <T> T string2Obj(String str, TypeReference<T> typeReference){
        if(StringUtils.isEmpty(str) || typeReference == null){
            return null;
        }
        try {
            return (T)(typeReference.getType().equals(String.class)? str : objectMapper.readValue(str,typeReference));
        } catch (Exception e) {
            log.warn("Parse String to Object error",e);
            return null;
        }
    }

    public static <T> T string2Obj(String str,Class<?> collectionClass,Class<?>... elementClasses){
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass,elementClasses);
        try {
            return objectMapper.readValue(str,javaType);
        } catch (Exception e) {
            log.warn("Parse String to Object error",e);
            return null;
        }
    }

    public static void main(String[] args) {
        TestPojo testPojo = new TestPojo();
        testPojo.setName("Geely");
        testPojo.setId(666);

        //{"name":"Geely","id":666}
        String json = "{\"name\":\"Geely\",\"color\":\"blue\",\"id\":666}";
        TestPojo testPojoObject = JsonUtil.string2Obj(json,TestPojo.class);
//        String testPojoJson = JsonUtil.obj2String(testPojo);
//        log.info("testPojoJson:{}",testPojoJson);

        log.info("end");

//        User user = new User();
//        user.setId(2);
//        user.setEmail("
[email protected]
"); // user.setCreateTime(new Date()); // String userJsonPretty = JsonUtil.obj2StringPretty(user); // log.info("userJson:{}",userJsonPretty); // User u2 = new User(); // u2.setId(2); // u2.setEmail("[email protected]"); // // // // String user1Json = JsonUtil.obj2String(u1); // // String user1JsonPretty = JsonUtil.obj2StringPretty(u1); // // log.info("user1Json:{}",user1Json); // // log.info("user1JsonPretty:{}",user1JsonPretty); // // // User user = JsonUtil.string2Obj(user1Json,User.class); // // // List<User> userList = Lists.newArrayList(); // userList.add(u1); // userList.add(u2); // // String userListStr = JsonUtil.obj2StringPretty(userList); // // log.info("=================="); // // log.info(userListStr); // // // List<User> userListObj1 = JsonUtil.string2Obj(userListStr, new TypeReference<List<User>>() { // }); // // // List<User> userListObj2 = JsonUtil.string2Obj(userListStr,List.class,User.class); System.out.println("end"); } }

相關推薦

Json序列工具

package com.mmall.util; import com.google.common.collect.Lists; import com.mmall.pojo.Category; import com.mmall.pojo.TestPojo; import c

Json序列幫助

lac this nbsp orm fault ota 序列 time rep public static class Json { public static object ToJson(this string Json) {

序列工具

str ktr trace print ati serialize new post trac import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.O

Java 序列工具

pub ear base64 找不到 ror stream ger public 工具類 import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sun.misc.BASE64Decoder; imp

序列與反序列工具

package com.zp.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.

java序列工具

class SerializationUtils { private SerializationUtils() { throw new UnsupportedOperationException(); } public static void writeObje

為Redis配置自定義fastJson序列工具

    alibaba.fastjson內部已經提供了對Redis儲存物件序列化的工具類GenericFastJsonRedisS

Json序列java工具

java對象 writev ctype imp date eval 取消 cti empty json序列化通用工具類(java)>為了支持此工具類的正常使用,先導入以下jar包 1.lombok包是一個簡化java冗余代碼的jar包,實際開發中很方便在maven的p

C# webApi----H5_app後臺制作(3)--序列無法接收Json格式的數據

過程 轉換成 無法 png bsp 測試 數據請求 請求 word 今天使用fiddler軟件對webapi發送json格式數據請求時,後臺無法接收到數據 首先介紹一下什麽是序列化 序列化: 將數據結構或對象轉換成二進制串的過程 反序列化:將在序列化過程中所生成的二進制串

python3數據序列工具json

數據序列化 json序列化 pickle序列化 文件中默認只能存字符串,是不能存字典、二進制這種特殊類型的數據的,如果想把字典格式的數據存入到文件中,需要轉換一下數據類型data = {"Name":"XiaoMing","Age":22

json序列時定制支持datetime型,和到中文讓他保留中文形式

turn json class complex json序列化 默認 mps return ascii json序列化時,可以處理的數據類型有哪些?如何定制支持datetime類型 自定義時間序列化轉換器 import json from json import JSO

Python3 shevel模塊,更高級的json序列數據型模塊(比pickle更高級)

evel 圖片 alt http python mage 字典 pickle png 直接將數據類型以字典的格式 存到文件中去。 直接.get讀取出來, Python3 shevel模塊,更高級的json序列化數據類型模塊(比pickle更高級)

JSON繼承JsonConverter序列與反序列重寫屬性

首先自定義一個JSON類,繼承JsonConverter,把類的屬性重寫到JSON中. using System; using System.Collections.Generic; using System.Linq; using Sys

MyBatis 物件到json格式序列工具typeHandler

用途:POJO物件可以是任何型別,List,Map等等,轉換為json字串儲存到資料庫,查詢出來的時候自動轉換為相應的物件,而非人工操作轉換,直接貼上程式碼如下: package com.xyy.typehandler; import java.io.IOException; import j

JsonUtils的封裝實現Object與json序列與反序列

public class JsonUtils { // 定義jackson物件 private static final ObjectMapper MAPPER = new ObjectMapper(); /** * 將物件轉換成json字串。 * <

Swifter.Json -- 在 .Net 平臺上的一個功能強大,簡單易用,穩定又不失高效能的 JSON 序列和反序列工具

Swifter.Json Github Wiki 在 .Net 平臺上的一個功能強大,簡單易用,穩定又不失高效能的 JSON 序列

JSON序列,並解碼成為 datagridview 的 datasource

GridView cli obj get connect spa handle string bindings // encode List<clientState> clientList = new List

webapi “ObjectContent`1”型未能序列內容型“application/xml; charset=utf-8”的響應正文。

ted 分享 global format nbsp ica type .com 什麽 今天在來一發 webapi的一個知識點 相信用過webapi的對這個錯誤 已經看在眼裏 痛在心裏了把 我百度也搜了一下 看了一下 然後發現他們的解決辦法 並沒有什麽軟用

自定義redis序列工具

我們 utils 字節數 pac keys ted ive onu 問題 redis一個優點就是可以將數據寫入到磁盤中。 我們知道寫入磁盤的數據實際上都是以字節(0101這樣的二進制數據)的形式寫入的。 這意味著如果我們要將一個對象寫入磁盤,就必須將這個對象序列化。 jav

Asp.Net Core中Json序列處理整理

忽略 化工 res ref 工具 使用 asp.net ctr ide 一、Asp.Net Core中的Json序列化處理使用的是Newtonsoft.Json,更多參考:C# Newtonsoft.Json JsonSerializerSettings配置序列化操作,C#