harshavmb
harshavmb

Reputation: 3872

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.

Upvotes: 1

Views: 1747

Answers (1)

Sharon Ben Asher
Sharon Ben Asher

Reputation: 14328

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;
        }
    }
}

Upvotes: 4

Related Questions