1. 程式人生 > >Java json反序列化

Java json反序列化

package com.nuanshui.frms.exchange.utils;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.ser.FilterProvider;

import
java.io.IOException; public class JacksonUtils { private JacksonUtils() { //default construct } /** * Json反序列化 * * @param val * @param cls * @return * @throws JsonParseException * @throws IOException * @desc 1.實體上 * @JsonInclude(Include.NON_NULL) 將該標記放在屬性上,如果該屬性為NULL則不參與序列化 * 如果放在類上邊,那對這個類的全部屬性起作用 * Include.Include.ALWAYS 預設 * Include.NON_DEFAULT 屬性為預設值不序列化 * Include.NON_EMPTY 屬性為 空(“”) 或者為 NULL 都不序列化 * Include.NON_NULL 屬性為NULL 不序列化 * 2.程式碼上 * ObjectMapper mapper = new ObjectMapper(); * mapper.setSerializationInclusion(Include. * NON_NULL); * 通過該方法對mapper物件進行設定,所有序列化的物件都將按改規則進行系列化 * Include.Include.ALWAYS 預設 * Include.NON_DEFAULT 屬性為預設值不序列化 * Include.NON_EMPTY 屬性為 空(“”) 或者為 NULL 都不序列化 * Include.NON_NULL 屬性為NULL 不序列化 */
public static <T> T parseJsonFromString(String val, Class<T> cls) throws JsonParseException, IOException { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return mapper.readValue(val, cls); } public
static String serialObject(Object obj) throws JsonProcessingException { return serialObject(obj, null); } public static String serialObject(Object obj, FilterProvider filters) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); if (filters != null) { mapper.setFilterProvider(filters); } //把null替換為""字串 mapper.getSerializerProvider().setNullValueSerializer( new JsonSerializer<Object>() { @Override public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException { gen.writeString(""); } }); return mapper.writeValueAsString(obj); } public static JsonNode parseJsonFromString(String val) throws JsonProcessingException, IOException { ObjectMapper mapper = new ObjectMapper(); return mapper.readTree(val); } }