简体   繁体   中英

how to use @JsonProperty in this case - jackson API with lombok

I know how to use @JsonProperty in jackson API but the below case is different.

I've below json snippet.

{"results":[{"uniqueCount":395}

So, to parse with jackson API the above json, I've written below java pojo class.

package com.jl.models;

import lombok.Data;

@Data
public class Results
{
    private int uniqueCount;

}

Later, I got to parse below similar json snippet.

{"results":[{"count":60}

Now, the problem here is I'm unable to parse this json with Results class as it expects a string uniqueCount .

I can easily create another java pojo class having count member variable but I've to create all the parent java classes having instance of Results class.

So, is there any way I can customize Results class having lombok behaviour to parse both the json without impacting each others?

Thanks for your help in advance.

You can use Jackson's @JsonAnySetter annotation to direct all unknown keys to one method and there you can do the assignment yourself:

@Data
public class Results
{
    private int uniqueCount;

    // all unknown properties will go here
    @JsonAnySetter
    public void setUnknownProperty(String key, Object value) {
        if (key.equals("count")) {
            uniqueCount = (Integer)value;
        }
    }
}

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