Rumi
Rumi

Reputation: 81

Creating a POJO from JSON and retrieving the properties using the POJO classes

I am trying to convert a JSON file into POJO (following Lombok) and then retrieve the properties of the JSON using the POJO classes. This is my JSON file:

{
  "pickEventActivities": [
    {
      "orderId": "215",
      "line": 3,
      "pickByType": "EACH",
      "pickGtin": "0007",
      "pickedUser": "testUsr",
      "activations": [
        {
          "activationType": "SERIAL",
          "activationValue": "314561"
        }
      ]
    }
  ]
}

Following is the POJO class which contains the list of in pickEventActivities.

@Data
public class PickEvent {
    @SerializedName("pickEventActivities")
    @Expose
    private List<PickEventActivity> mPickEventActivities;
}

Other classes include:

public class Activation {
    @SerializedName("activationType")
    @Expose
    private String mActivationType;
    
    @SerializedName("activationValue")
    @Expose
    private String mActivationValue;
}

And following the class name PickEvent Activity:

@Data
public class PickEventActivity {
    @SerializedName("activations")
    @Expose
    private List<Activation> mActivations;
    
    @Expose
    @SerializedName("orderId")
    private String mOrderId;
    
    @Expose
    @SerializedName("line")
    private Long mLine;
    
    @Expose
    @SerializedName("pickByType")
    private String mPickByType;
    
    @SerializedName("pickGtin")
    @Expose
    private String mPickGtin;
    
    @SerializedName("pickedUser")
    @Expose
    private String mPickedUser;
}

And my final class where I am calling the POJO is:

public class AssertionPickEventActivity {
    PickEvent pickEvent;

    @Test
    public void beforeTest() throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        PickEvent pickEvent = mapper.readValue(new File("src/test/resources/json/pickEvent1.json"), PickEvent.class);
        System.out.println(pickEvent);
    }
}

The error I am getting is:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field 
"pickEventActivities" (class picking.event.model.PickEvent), not marked as ignorable (one known property: "mpickEventActivities"])

Any help will be appreciated. Thank you

Upvotes: 0

Views: 1610

Answers (1)

Jo&#227;o Dias
Jo&#227;o Dias

Reputation: 17460

You are mixing GSON annotations @SerializedName and @Expose with Jackson ObjectMapper. You should use @JsonProperty annotation instead as follows:

@Data
public class PickEvent {
    @JsonProperty("pickEventActivities")
    private List<PickEventActivity> mPickEventActivities;
}

You must do the same for all the other classes.

Upvotes: 2

Related Questions