Home > Enterprise >  How to turn a String into ArrayList<Details>?
How to turn a String into ArrayList<Details>?

Time:10-01

The browser sends the following object to the backend:

enter image description here

Now I would like to store the data in my database. So I have an entity that looks like this:

@Entity
public class NewQuote {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String description;
    @ElementCollection(targetClass = Details.class)
    private List<Details> details = new ArrayList<>();

    public NewQuote(String description, ArrayList<Details> details) {
        this.description = description;
        this.details = details;
    }
@Embeddable
public class Details {
    private String description;
    private String label;

    public Details(String description, String label) {
        this.description = description;
        this.label = label;
    }

    public Details() {}
}

Controller

@PostMapping(value = "/save-quote", produces = MediaType.APPLICATION_JSON_VALUE)
public void saveQuote(@RequestBody Map<String, String> data) {
    newQuoteService.saveQuote(data);
}

Service

public void saveQuote(Map<String, String> data) {
    JSONObject json = new JSONObject(data);
    NewQuote newQuote = new NewQuote(
            json.getAsString("description"),
            json.getAsString("details")
    );
    newQuoteRepository.save(newQuote);
}

I am getting an error because json.getAsString("details") should not be a string of course. So how can I turn it to ArrayList<Details>?

CodePudding user response:

Add a DTO to manage your json response. You don't need to explicitly use JSONObject because spring already manage the process of mapping under the wood with Jackson. Also, it is not a good practice to pass your Entities directly into the controller methods.

NewQuoteDto.java

public class NewQuoteDto {
    
    private Long id;
    private String description;
    private List<Details> details = new ArrayList<>();

    public NewQuoteDto() {
       
    }

    // getter and setter or you can use lombok
}

DetailDto.java

public class DetailDto {
    private String description;
    private String label;

    public DetailDto() {}

    // getter and setter or you can use lombok
}

Controller

@PostMapping(value = "/save-quote", produces = MediaType.APPLICATION_JSON_VALUE)
public void saveQuote(@RequestBody NewQuoteDto dataDto) {
    // here you map dataDto to your model before you call saveQuote
    NewQuote data = mapper.map(dataDto, NewQuote.class); // if you use ModelMapper library.
    newQuoteService.saveQuote(data);
}

For custom mapping take look here.

  • Related