Use of JsonIgnoreProperties specific property dese

2020-07-13 13:00发布

问题:

I stumbled upon some code that adds JsonIgnoreProperties to a property that doesn't exists in class, but exists in JSON, e.g.:

@JsonIgnoreProperties({"ignoreprop"})
public class VO {
   public String prop;
}

When JSON is

{ "prop":"1", "ignoreprop":"9999"}

I wonder if ignoring properties has any advantage(s) performance-wise or is it just redundant code?

Annotation that can be used to either suppress serialization of properties (during serialization), or ignore processing of JSON properties read (during deserialization).

EDIT

Is there an advantage(s) ignoring specific property over all (with @JsonIgnoreProperties(ignoreUnknown=true))?

回答1:

I wonder if ignoring properties has any advantage

Yes, it is used a lot for forward-compatibility in services. Let's say you have Services A and B. Currently A sends requests to B with some JSON objects.
Now you want to support a new property in the JSON. If you have this feature you are able to let A start sending the new property before B knows how to handle it. Decoupling the development processes of those two services.

ignoring specific property over all

This case does have some minor performance advantages. First, it doesn't try to parse this property which can be a simple string or complex object/array. Second, it helps you avoid handling an exception. Think that all the following can be valid calls and you only care about prop:

{ "prop":"1", "ignoreprop":"9999"}

{ "prop":"1", "ignoreprop":{ "a": { "key": "value", "foo": false }}}

{ "prop":"1", "ignoreprop":[1,2,3,4,5,6..... 1000000]}


回答2:

From the documentation, mainly the purpose of use this is To ignore any unknown properties in JSON input without exception: which is better not to popup exception when properties are not found either in class or JSON, and this might helps serializing faster docs

Example:

// to prevent specified fields from being serialized or deserialized

// (i.e. not include in JSON output; or being set even if they were included) @JsonIgnoreProperties({ "internalId", "secretKey" })

// To ignore any unknown properties in JSON input without exception: @JsonIgnoreProperties(ignoreUnknown=true)

Starting with 2.0, this annotation can be applied both to classes and to properties. If used for both, actual set will be union of all ignorals: that is, you can only add properties to ignore, not remove or override. So you can not remove properties to ignore using per-property annotation.