我有一张桌子
Country State
USA Texas
USA Alasca
India Delhi
India Bombay
India Madras
Russia Mosco
Russia Petersberg
Germany Berlin
China Beijing
China Tibet
Turkey Antioch
我需要在两个选择框中显示这些项目, 国家和州。当从国家选择框中选择美国时,德克萨斯州和阿拉斯加州应显示在州选择框中。 所以我需要创建一个Json对象
[{Country:USA, State:{{statename:Texas},{statename:Alasca}}},
{Country:India, State:{{statename:Delhi}, {statename:Bombay}, {statename:Madras}}},
{Country:Germany, State:{{statename:Berlin}},
{Country:Russia, State:{{statename:Mosco},{statename:Petersberg}}},
{Country:China, State:{{statename:Beijing}, {statename:Tibet}}},
{Country:turkey, State:{{statename:Antioch}}}
]
目前,我使用两个单独的sqls来分别获取国家和州。我使用Java类 国家/地区
public class Country implements Serializable {
String country;
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
我使用DAO作为
public List<Country> extractData(ResultSet rs) throws SQLException,
DataAccessException {
List<Country> list = new ArrayList<Country>();
while (rs.next()) {
Country obj = new Country();
obj.setCountry(rs.getString(1).trim());
list.add(obj);
}
return list;
}
我得到的对象为:
[{country:USA}, {country:India}, {country:Germany}, {country:Russia}, {country:China}, {country:turkey}]
以同样的方式,我创建了用于提取数据的状态和代码的类,我将状态设为
[ {state:Texas} {state:Alasca}, {state:Delhi}, {state:Bombay}, {state:Madras}, {state:Berlin}, {state:Mosco}, {state:Petersberg} {state:Beijing}, {state:Tibet}, {state:Antioch}]
这可以分别在选择框中显示。
但我需要以下列方式将对象正确显示在选择框中。
[{Country:USA, State:{{statename:Texas},{statename:Alasca}}},
{Country:India, State:{{statename:Delhi}, {statename:Bombay}, {statename:Madras}}},
{Country:Germany, State:{{statename:Berlin}},
{Country:Russia, State:{{statename:Mosco},{statename:Petersberg}}},
{Country:China, State:{{statename:Beijing}, {statename:Tibet}}},
{Country:turkey, State:{{statename:Antioch}}}
]
我可以创建一个java类,
class CountryState{
string country;
List <State> state;
public String getCountry()
{
return country;
}
public void setCountry(String country){
this.country=country;
}
public List<State> getState(){
return state;
}
public void setState(List<State> state)
{
this.state.add(state);
}
}
class State{
String statename;
public String getStatename()
{
return statename;
}
public void setStatename(String statename){
this.statename=statename;
}
我需要知道如何将结果集中的值存储到这样的对象中并生成所需的JSON对象。
答案 0 :(得分:0)
在JAVA中为来自数据库的数据对象创建一个pojo,并在该pojo上使用JSON转换库,就像使用GSON或Jackson一样。
提示:您可能需要将您的查询更改为按国家/地区分组,并且您可能需要映射到一个国家/地区的状态集合。