Home > database >  Multiple DTOs manual initialize
Multiple DTOs manual initialize

Time:12-29

in Microservice, we post multiple dtos data as string json.

Controller:

@RequestMapping(value="/json",method = RequestMethod.POST)
public String getjson(@RequestBody String json) {

   ///Service process
}

Post Json:

{
"dtos":{
    "Dto1":{   
        "name":"Dto1 Name Field",
        "filter":[
            {"key":"f1","value":1},
            {"key":"f2","value":10}
        ]
    },
    "Dto2":{
        "city":"Newyork",    
        "filter":[
            {"key":"f1","value":1},
            {"key":"f2","value":10},
    {"key":"f3","value":10}
        ]
    }
},
"page":1
}

DTO:

public class Dto1{
   private String name;
}
public class Dto2{
   private String city;
}

Dto1 and Dto2 is java DTO object name. how to convert string json to java objects?

CodePudding user response:

You can create a new DTO that contains all attrs and receive in request:

public class Filter{
    private String key;
    private int value;
}

public class Dto1{
    private String name;
    private List<Filter> filter;
}

public class Dto2{
    private String city;
    private List<Filter> filter;
}

public class Dtos{
    public Dto1 dto1;
    public Dto2 dto2;
}

public class DtoToReceiveInRequest{
    private Dtos dtos;
    private int page;
}

Controller

@PostMapping
public String getjson(@RequestBody DtoToReceiveInRequest json) {

   ///Service process
}

CodePudding user response:

You can use the ObjectMapper from the jackson library, like below.

String json = "";
ObjectMapper objectMapper = new ObjectMapper();
Dto1 dto = objectMapper.readValue(json, Dto1.class);

But in your particular example, you don't have to have two DTO classes. You can encapsulate values in one DTO and have the list of different instances of that DTO in a json format.

NB. The json string should be a representation of the preferred class you want to retrieve, eg Dto1.java.

  • Related