开发时遇见这么一个情况,对接放发出的json格式不确定,这里的不确定是json中的字段不确定,以往都是采用gson进行实体和json的转换,但是找了挺长时间,还是没找到gson中可以解决这个情况的办法,博友们有知道的,请告知一二,跪谢。
废话不多说,这种办法最终使用jackson解决。
解决办法:
json转换成的实体类加注解@JsonIgnoreProperties(ignoreUnknown = true),注意这是类级别的注解。
@JsonIgnore注解用来忽略某些字段,可以用在Field或者Getter方法上,用在Setter方法时,和Filed效果一样。这个注解只能用在POJO存在的字段要忽略的情况,不能满足现在需要的情况。
@JsonIgnoreProperties(ignoreUnknown = true),将这个注解写在类上之后,就会忽略类中不存在的字段,可以满足当前的需要。这个注解还可以指定要忽略的字段。使用方法如下:
 @JsonIgnoreProperties({ "internalId", "secretKey" })
 指定的字段不会被序列化和反序列化。
附上一个转换的工具类
package com.*******.****.drp.util;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
/** 
* @Description:
* @author :******| paranoia_zk@yeah.net 
* @date :2017年6月8日 上午10:32:04 
*/
@Slf4j
public class JacksonUtil {
	private final static ObjectMapper objectMapper = new ObjectMapper();
    static {
        objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
        objectMapper.configure(JsonParser.Feature.INTERN_FIELD_NAMES, true);
        objectMapper.configure(JsonParser.Feature.CANONICALIZE_FIELD_NAMES, true);
        objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }
    public static String encode(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonGenerationException e) {
            log.error("encode(Object)", e); //$NON-NLS-1$
        } catch (JsonMappingException e) {
            log.error("encode(Object)", e); //$NON-NLS-1$
        } catch (IOException e) {
            log.error("encode(Object)", e); //$NON-NLS-1$
        }
        return null;
    }
    /**
     * 将json string反序列化成对象
     *
     * @param json
     * @param valueType
     * @return
     */
    public static <T> T decode(String json, Class<T> valueType) {
        try {
            return objectMapper.readValue(json, valueType);
        } catch (JsonParseException e) {
            log.error("decode(String, Class<T>)", e);
        } catch (JsonMappingException e) {
            log.error("decode(String, Class<T>)", e);
        } catch (IOException e) {
            log.error("decode(String, Class<T>)", e);
        }
        return null;
    }
}
 jar包这里下载 jsonproperties的使用
 

京公网安备 11010502036488号