vendredi 26 février 2021

How to map nested JSON into object model and test it in SpringBoot

Hi everyone I have a nested JSON that I have to map into 3 object models. I have to create CarResponse, Car and CarValue models.

Here is my JSON file:

{
  "car": [
    {
      "shop": "Audi Germany",
      "date": 1573599600000,
      "values": [
        {
          "name": "Audi Xl",
          "age": "2020",
          "country": "Germany"
        },
        {
          "name": "Audi i",
          "age": "2021",
          "country": "France"
        },
        {
          "name": "Bmw Xl",
          "age": "2020",
          "country": "Spain"
        },
        {
          "name": "Citroen",
          "age": "1990",
          "country": "France"
        }
}]
}

So I created 3 modals.

public class CarResponse {

    List<Car> quotes = new ArrayList<Car>();
    //Getters setters
}

public class Car {

    private String shop;
    private String date;
 //Getters setters and toString
}

public class CarValue {

    private String name;
    private String country;
    private Long age;
    //Getters setters and toString
}

I am not sure if this is a right way. Because when I try to write a test on it, I am not sure where to start.

I created DataLoader class to read from JSON.

@Service
public class DataLoader {

  @Value("${DataLoader.url}") private String urlStr;

  public QuoteResponse load() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return mapper.readValue(urlStrl, QuoteResponse.class);
  }

}

And how should I write a test for it now? Any advice highly appreciated> Thanks!

Aucun commentaire:

Enregistrer un commentaire