I have two table country
and city
in mysql
dababase and i make a query to return records like that as List<myDTO>
:
1,france,1,paris
1,france,2,marseille
1,france,3,lion
....
MyDTO
public class MyDTO {
public Integer idLvl1;
public String nameLvl1;
public Integer idLvl2;
public String nameLvl2;
public MyDTO(Integer idLvl1, String nameLvl1, Integer idLvl2, String nameLvl2) {
this.idNiv1 = idLvl1;
this.nomNiv1 = nameLvl1;
this.idNiv2 = idLvl2;
this.nomNiv2 = nameLvl2;
}
How can i convert it to json object to avoid the repeating country :
[
{"idNiv1" :1,"nameLvl1":"France","cities":[{"idNiv2":1,"nameLvl2":"paris"}]}
{"idNiv1" :1,"nameLvl1":"France","cities":[{"idNiv2":2,"nameLvl2":"marseille"}]}
{"idNiv1" :1,"nameLvl1":"France","cities":[{"idNiv2":3,"nameLvl2":"lion"}]}
....
]
to
[
{
"idNiv1" :1,
"nameLvl1":"France",
"cities":[
{ "idNiv2":1,"nameLvl2":"paris" } ,
{ "idNiv2":2,"nameLvl2":"marseille" } ,
{ "idNiv2":3,"nameLvl2":"lion" }
]
}
....
]
Create additional classes for country and city. Transform the flat structure to nested structure of country and cities as shown below:
The final Collection of Country will result is the desired JSON.
You can write Wrapper DTO on top of Your MyDTO and then use any available json libraries like Google's Gson to convert to required JSON format.
Regards, Sakumar
You can use Google's Gson in this case :
Update: You can call
getJSONFromResultSet
method like below :