AKJ
AKJ

Reputation: 809

Mapping JSON string to POJO with differing attributes

I have a jsonString that looks like this:

String jsonString = "{\"ID_BUY\":1234567}";

And I have a POJO:

@Data
@NoArgsConstructor
@SuperBuilder
@JsonInclude(Include,NON_EMPTY)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Order() {
  @JsonProperty("ID_BUY")
  private String identityBuy;
}

I am using ObjectMapper:

ObjectMapper mapper = new ObjectMapper()
  .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true)
  .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
  .configure(MapperFeature.USE_ANNOTATION, true);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()));

When I perform

Order output = mapper.readValue(jsonString, Order.class);

and print out

System.out.println(output.toString());

I notice that the identityBuy has a value of null.

Is there a way to get the mapper to take note of the @JsonProperty annotation?

Could someone point me in the right direction.

Upvotes: 0

Views: 459

Answers (1)

Arun Sai
Arun Sai

Reputation: 1972

It was working fine for me.

Test.java

import com.fasterxml.jackson.databind.ObjectMapper;
import com.test.check.Order;

public abstract class Test {

    public static void main(String[] args) throws Exception {

        ObjectMapper map = new ObjectMapper();

        String op = "{\"ID_BUY\":1234567}";
        Order orderObj = map.readValue(op, Order.class);

        System.out.println("printing output-->" + orderObj);
        System.out.println("printing output-->" + orderObj.toString());

    }

}

Order.java

import com.fasterxml.jackson.annotation.JsonProperty;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;

@Setter
@Getter
@Data
public class Order {

    @JsonProperty("ID_BUY")
    private String arun;

}

Output:

printing output-->Order(arun=1234567)
printing output-->Order(arun=1234567)

Upvotes: 1

Related Questions