将包含重复字段的对象转换为JSON

时间:2015-11-14 21:36:23

标签: java mysql sql json spring-mvc

我在country dababase中有两个表citymysql,我会查询以返回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;
    }

如何将其转换为json对象以避免重复的国家/地区:

[ 
  {"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"}]} 
  ....
]

[ 
  {
     "idNiv1" :1,
     "nameLvl1":"France",
     "cities":[
                { "idNiv2":1,"nameLvl2":"paris" } ,
                { "idNiv2":2,"nameLvl2":"marseille" } ,
                { "idNiv2":3,"nameLvl2":"lion" }
              ]
  }
  ....
]

3 个答案:

答案 0 :(得分:2)

在这种情况下,您可以使用Google的Gson

models

<强>更新 您可以调用public String getJSONFromResultSet(ResultSet rs, String key) { Map json = new HashMap(); List list = new ArrayList(); if (rs != null) { try { ResultSetMetaData mData = rs.getMetaData(); while (rs.next()) { Map<String, Object> columns = new HashMap<String, Object>(); for (int columnIndex = 1; columnIndex <= mData.getColumnCount(); columnIndex++) { if (rs.getString(mData.getColumnName(columnIndex)) != null) { columns.put(mData.getColumnLabel(columnIndex), rs.getString(mData.getColumnName(columnIndex))); } else { columns.put(mData.getColumnLabel(columnIndex), ""); } } list.add(columns); } } catch (SQLException e) { e.printStackTrace(); } json.put(key, list); } return new Gson().toJson(json); } 方法,如下所示:

getJSONFromResultSet

答案 1 :(得分:1)

为国家/地区和城市创建其他课程。将平面结构转换为国家和城市的嵌套结构,如下所示:

public class Country {

    Integer idLvl1;
    String  nameLvl1;

    public Country(Integer idLvl1, String  nameLvl1) {
    }

    List<City> cities;

}

public class City {

    Integer idLvl2;
    String  nameLvl2;

    public City(Integer idLvl2, String  nameLvl2) {
    }
}

public class MyDTOConverter {

    public static Collection<Country> covert(List<MyDTO> dtos){
        Map<Integer, Country> countries = new LinkedHashMap<Integer, Country>();
        for (MyDTO myDTO : dtos) {
            //First adding the country if it doesn't exist
            if (!countries.containsKey(myDTO.idLvl1)){
                countries.put(myDTO.idLvl1, new Country(myDTO.idLvl1, myDTO.nameLvl1));
            }

            //Adding city in the existing country.
            countries.get(myDTO.idLvl1).cities.add(new City(myDTO.idLvl2, myDTO.nameLvl2));
        }

        return countries.values();
    }

}

最终的国家集合将产生所需的JSON。

答案 2 :(得分:0)

您可以在MyDTO上编写Wrapper DTO,然后使用Google的Gson等任何可用的json库转换为所需的JSON格式。

此致 Sakumar