Home > other >  Use DTO to map JSON to final object, or just parse JSON?
Use DTO to map JSON to final object, or just parse JSON?

Time:04-21

I have some json object that looks like this:

{
   "make":"Volvo",
   "model":"240",
   "metadata":{
      "color":"white",
      "year":"1986",
      "previousOwner":"Joe",
      "condition":"good"
   }
}

And I want to turn this JSON into List<Car>, which is comprised of the following objects:


public class Car {

    private String make;

    private String model;

    private CarMetadata carMetadata;

}

public class CarMetadata {

    private Body body;

    private History history;

}

public class Body {

    private String color;

    private String condition;

}

public class History {

    private String previousOwner;

    private String year;

}

So essentially the point is that the object I want to turn it into (Car) is very nested, whereas my JSON is not very nested. In reality the "Car" object is actually much more nested than this example I'm showing.

I was thinking of two options:

  1. Create a CarDTO object to represent my input JSON, do objectMapper.readValue(json, CarDTO.class), then map CarDTO to Car to create my List<Car>.

  2. Just parse the JSON and create the final List<Car> object in the first place.

I don't want to create an unnecessary DTO, but I also don't want to mess with parsing this JSON.

Is there a best practice in this scenario, and would this even be a valid use of a DTO?

CodePudding user response:

Use a DTO.

Although you can deserialize from json directly to your domain class, their structure differs so you would have to create a custom deserializer... DO NOT TRY THIS AT HOME. I've been there and it's completely not worth the hassle.

Use the DTO to parse the json into a POJO, then map the DTO to the domain object.

This will decouple the transport from your domain object, allowing both to change freely with only the mapping code being affected. It's also way easier to write, understand, test and debug.

  • Related