ObjectMapper工具類(json轉List


 

 

一 json轉實體類\實體類轉json\json轉List<T>

 

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;







public class JsonUtil {
    private static ObjectMapper objectMapper = new ObjectMapper();
    static {
       //忽略屬性為null
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //忽略多余屬性
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static String objectToString(Object object)  {
        
        try {
            return objectMapper.writeValueAsString(object);

        } catch (JsonProcessingException e) {
            // TODO: handle exception
        }
        return null;
    }

    public static <T> T stringToObject(String json,Class<T> object) throws IOException {
        return objectMapper.readValue(json,object);
    }
    
    public static <T> List<T>   stringToList(String json,Class<T> object){
        try {
            CollectionType listType = objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, object);
            List<T> list = objectMapper.readValue(json, listType);
            return list;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM