简体   繁体   English

使用Jackson将对象转换为json时忽略未设置原始类型

[英]Ignoring not set primitive type while converting an object to json using jackson

I have a class which looks like below:- 我有一堂课,看起来像下面:

@JsonSerialize(include = Inclusion.NON_EMPTY)
public class JsonPojo {
    private int intVal;
    private String strVal;

    public int getIntVal() {
    return intVal;
    }

    public void setIntVal(int intVal) {
    this.intVal = intVal;
    }

    public String getStrVal() {
    return strVal;
    }

    public void setStrVal(String strVal) {
    this.strVal = strVal;
    }
}

If I am having an instance of JsonPojo in which the int field is not set then while converting it to json jackson is assigning it a default 0 as shown below:- 如果我有一个JsonPojo实例,其中未设置int字段,则在将其转换为json jackson时为其分配默认值0,如下所示:-

public static void main(String[] args) {
    JsonPojo jsonPojo = new JsonPojo();
    jsonPojo.setStrVal("Hello World");
    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false);
        String json = mapper.writeValueAsString(jsonPojo);
        System.out.println(json);
    } catch (Exception e) {

    }

 }

This will output:- {"intVal":0,"strVal":"Hello World"} 这将输出:- {"intVal":0,"strVal":"Hello World"}

Is there a way I can ignore intVal in Json output when intVal is not set without converting the datatype of intVal to Integer ? 有没有一种方法,我可以忽略intVal在JSON输出时intVal也不是没有的数据类型转换设置intValInteger If I convert intVal to Integer then when this value is not set it will be null & doing JsonSerialize(include = Inclusion.NON_EMPTY) will skip intVal during the conversion to json. 如果我转换intVal为整数,然后当这个值未设置这将是空和做JsonSerialize(include = Inclusion.NON_EMPTY)将跳过intVal转换为JSON过程中。

But I want to know if it is possible to achieve the same behavior without converting intVal to Integer from int ? 但是我想知道是否有可能在不将intValint转换为Integer情况下实现相同的行为?

I am using jackson 1.9. 我正在使用杰克逊1.9。

Inclusion.NON_EMPTY should do what you expect. Inclusion.NON_EMPTY应该可以达到您的期望。 From the documentation: 从文档中:

Value that indicates that only properties that have values that values that are null or what is considered empty are not to be included. 表示仅包含值为空或视为空的值的属性的值。

Java primitive int is by default 0 (this is considered empty). Java原始int默认情况下为0(这被认为是空的)。 So if you never set it or you set it to 0 the output should be {"strVal":"Hello World"} I tried this on jackson 2.6.3 and seems to work so I assume there is an issue on 1.9 因此,如果您从未设置它或将其设置为0,则输出应为{"strVal":"Hello World"}我在杰克逊2.6.3上尝试过此方法,并且似乎可以正常工作,所以我认为1.9上存在问题

You could try the following and maybe works on 1.9: 您可以尝试以下操作,也许可以在1.9上运行:

@JsonInclude(Include.NON_DEFAULT)
private int intVal;

and remove include = Inclusion.NON_EMPTY 并删除include = Inclusion.NON_EMPTY

If 0 is a valid value you could add a flag to your pojo. 如果0是有效值,则可以在pojo中添加一个标志。 In you ever call the setter the flag should turn to true: 在您调用设置器时,标志应变为true:

    @JsonIgnore
    public boolean set = false;

    public Integer getIntVal() {
        if (!set) {
            return null;
        }
        return Integer.valueOf(intVal);
    }

    public void setIntVal(int intVal) {
        set = true;
        this.intVal = intVal;
    }

You could try @JsonInclude and @JsonProperty annotations from jackson.annotations package. 您可以尝试jackson.annotations包中的@JsonInclude@JsonProperty批注。 Here's the sample code : 这是示例代码:

JsonPojo class: JsonPojo类:

public class JsonPojo {
@JsonInclude(Include.NON_DEFAULT)
private int intVal;
@JsonProperty
private String strVal;

public int getIntVal() {
    return intVal;
}

public void setIntVal(int intVal) {
    this.intVal = intVal;
}

public String getStrVal() {
    return strVal;
}

public void setStrVal(String strVal) {
    this.strVal = strVal;
}}

Just in case if this is an acceptable solution: 以防万一这是可以接受的解决方案:

We can apply a custom filter to check whether intVal is set: 我们可以应用自定义过滤器来检查是否设置了intVal

@JsonSerialize(include = Inclusion.NON_EMPTY)
@JsonFilter("theFilter")
public class JsonPojo {
    private int intVal;
    private String strVal;

    private boolean isSetIntVal = false;

    @JsonIgnore
    public boolean getIsSetIntVal() {
        return isSetIntVal;
    }

    public int getIntVal() {
        return intVal;
    }

    public void setIntVal(int intVal) {
        this.intVal = intVal;
        this.isSetintVal = true;
    }

    public String getStrVal() {
        return strVal;
    }

    public void setStrVal(String strVal) {
        this.strVal = strVal;
    }
}

Implement a custom filter and then apply to the writer: 实现自定义过滤器,然后将其应用于编写器:

public static void main(String[] args) {
    SimpleBeanPropertyFilter theFilter = new SimpleBeanPropertyFilter() {
        @Override
        public void serializeAsField(Object pojo, JsonGenerator jgen, SerializerProvider provider,
                BeanPropertyWriter writer) throws Exception {

            if (!writer.getName().equals("intVal")) {
                writer.serializeAsField(pojo, jgen, provider);
                return;
            }
            if (((JsonPojo) pojo).getIsSetIntVal()) {
                writer.serializeAsField(pojo, jgen, provider);
            }

        }

    };

    JsonPojo jsonPojo = new JsonPojo();
    jsonPojo.setStrVal("Hello World");
    jsonPojo.setIntVal(0);
    try {
        ObjectMapper mapper = new ObjectMapper();
        FilterProvider filters = new SimpleFilterProvider().addFilter("theFilter", theFilter);
        mapper.configure(Feature.FAIL_ON_EMPTY_BEANS, false);
        String json = mapper.writer(filters).writeValueAsString(jsonPojo);
        System.out.println(json);
    } catch (Exception e) {

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 杰克逊将java对象原始属性转换为json字符串中的可选属性 - Jackson converting java object primitive properties as optional in json string 使用Jackson将json转换为Java对象的正确类型参考是什么 - What is correct type reference for converting the json into java object using jackson 我应该在使用Jackson时使用包装器还是原始类型作为字段 - Should I use a wrapper or primitive type as field while using Jackson 用Jackson提取JSON元数据(原始类型和名称) - Extracting JSON Metadata (primitive type and name) with Jackson 如何使用Jackson将反序列化的JSON反序列化为忽略键的对象? - How to deserialize a JSON to an object ignoring a key using Jackson? 使用杰克逊创建json并在某些情况下忽略对象 - Creating json using jackson and ignoring object in some condition 让Jackson将Json对象解析为原始String - Have Jackson parse Json object as primitive String 如何使用Jackson将对象转换为JSON时不使用默认值编组布尔属性 - how to not marshall boolean attributes with default values while converting object to JSON Using Jackson 如何使用Jackson将json转换为Java对象时忽略Map相关的括号 - How to ignore Map related braces while converting json to Java object using Jackson com.fasterxml.jackson.databind.JsonMappingException,同时将Json转换为Object - com.fasterxml.jackson.databind.JsonMappingException while converting Json to Object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM