简体   繁体   中英

Jackson JsonProperty

I am trying to parse json file using jackson @JsonProperty. I have an interesting problem at hand. One of the field name that is marked as @JsonProperty can be different based on input source. Example json files below

car1.json --> {"car": {"color": "yellow","type": "luxurySedan"}}
car2.json --> {"car": {"color": "yellow","modeltype": "SUV"}}

My Datamodel is something like

@Data
class Car {

   @JsonProperty("color")
   private String color; 

   @JsonProperty("type")
   private String type; // Don't want to use alias to solve above problem

 }

Second file car2.json does not get parsed. I tried following on field type to get value from a property file (using spring boot) but it is not working as expected. I am reluctant to use alias purely because I will have to change code if field name changes for any one of the file. Can someone help please

@JsonProperty(@Value("${car.type}")) // Compilation error (It's a spring boot project)
@JsonProperty("${car.type}") // Values not read

Your JSON doesn't appear to have a car node, so you can't use it as part of your @JsonProperty annotation. Generally speaking you only need to specify the individual node names rather than full paths, as they are evaluated relative to the root node. Where you have nested JSON structures it's conventional to encapsulate those inside a separate class so you still don't need to put full paths in.

class Car {

    @JsonProperty("color")
    private String color;

    @JsonProperty("type")
    private String type;

    @JsonProperty("modeltype")
    private String modelType;

    // The rest of the class
}

Should do the trick for the JSON that you've provided. If a property is missing from the source JSON then its value will simply be null in your Java object.

Your second sample of JSON fails because the Java object that Jackson is trying to unmarshal the JSON into doesn't declare a property named "modeltype" , and the default behaviour is to fail on unknown properties. That particular behaviour can be suppressed by adding the following class-level annotation:

@JsonIgnoreProperties(ignoreUnknown = true)

However this will cause Jackson to completely ignore any property for which there is no mapped field, so you will lose any data associated with unknown properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM