M.S.Naidu
M.S.Naidu

Reputation: 2289

How to ignore specific JSON field when converting JSON string to Java object?

I have the following json data as response from the Database, which I need to Map to my Java Pojo.

Json response:

{
"Vehicle" { 
 "travelMedium" : "road",
"CarList" : {
    "car": [
       {
        "company": "Maruthi",
         "color" : "red"   
       },
       {
        "company": "Honda",
         "color" : "black"   
       },
       {
        "company": "Swift",
         "color" : "white"   
       }
      ] 
  }
 }
}

Pojos

Class Vehicle {
  String travelMedium;
  List<Car> car;

}


Class Car {
  private company;
  private color;
}

I am using Jackson for this Deserialization which Will bind json to the Java object but the additional field CarList gives error. I want to avoid "CarList" field when it is binding (json string to Java Pojo).

I would like to know an approach to achieve this. Or any suggestions would be great.

Upvotes: 1

Views: 941

Answers (2)

lexicore
lexicore

Reputation: 43709

You actually don't want to ignore the CarList field, you want to "unwrap" it automatically.

You will probably need a wrapper class for this:

public class CarList {
    private final List<Car> car;
    @JsonCreator
    public CarList(@JsonProperty("car") List<Car> car) {
        this.car = car == null ? Collections.emptyList() : Collection.unmodifiableList(car);       
    }
    ... 
}

Then

public class Vehicle {
    private final String travelMedium;
    private final List<Car> car;
    @JsonCreator
    public CarList(@JsonProperty("travelMedium") String travelMedium,
                   @JsonProperty("CarList") CarList carList) {
        this.travelMedium = travelMedium;
        this.car = carList == null ? Collections.emptyList() : Collection.unmodifiableList(carList.getCar());
    }
    ... 
}

Upvotes: 0

gaganbm
gaganbm

Reputation: 2853

Maybe its not that clean. But if you want to avoid having this carList field in your pojo, you can do something like this :

You can provide a setter method and set the field you actually need.

@JsonProperty("carList")
public void setCarList(Map<String, List<Car>> cars) {
  this.car = cars.get("carList");
}

Upvotes: 2

Related Questions