json_3层格式_数据源DataSet
例如下面这个方法,得到了一个视图的数据包含了省份城市店铺
public DataSet GetData() { try { StringBuilder sql = new StringBuilder("SELECT PROVINCE_ID,PROVINCE_NAME,CITY_ID,CITY_NAME,DEALER_ID,DEALER_NAME "); sql.Append(" FROM VIEW_P_C_Data "); sql.Append(" WHERE 1=1 order by PROVINCE_NAME,CITY_NAME"); DataSet ds = dbManager.Query(sql.ToString()); return ds; } catch (Exception ex) { throw new Exception(ex.Message); } }
首先获取到数据DataSet ds = GetData();
声明:HashSet<string> vehicle_p = new HashSet<string>();
然后循环ds
foreach (DataRow row in ds.Tables[0].Rows)
{
}
循环里做一个复制判断,因为省份是重复的,城市也是。一对多的关系。所以不同城市相同省份时,对于json结构只要添加一次省份
bool exist_province = vehicle_p.Add(row["PROVINCE_NAME"].ToString());
bool exist_city = vehicle_p.Add(row["CITY_ID"].ToString());
//当省份不存在时,第一次添加
if (exist_province)
{
}else{
//相同省份不同城市时,
if (exist_city)
{
}else{
//相同城市,不同店铺时
}
}
PS:全部代码
public List<Text_Drive_Dealer> GetAllDealer() { List<Text_Drive_Dealer> list = new List<Text_Drive_Dealer>(); DataSet ds = GetData(); HashSet<string> vehicle_p = new HashSet<string>(); Text_Drive_Dealer t_dealer = null; List<Text_City> list_vm = null; Text_City vm = null; foreach (DataRow row in ds.Tables[0].Rows) { bool exist_province = vehicle_p.Add(row["PROVINCE_NAME"].ToString()); bool exist_city = vehicle_p.Add(row["CITY_ID"].ToString()); if (exist_province) { //当省份不存在时,第一次添加 t_dealer = new Text_Drive_Dealer(); t_dealer.ProvinceID = row["PROVINCE_ID"].ToString(); t_dealer.ProvinceName = row["PROVINCE_NAME"].ToString(); //第一次添加城市 vm = new Text_City(); vm.CityID = row["CITY_ID"].ToString(); vm.CityName = row["CITY_NAME"].ToString(); //第一次添加该城市的特约店 Text_dealer td = new Text_dealer(); td.DealerID= row["DEALER_ID"].ToString(); td.DealerName = row["DEALER_NAME"].ToString(); List<Text_dealer> list_td = new List<Text_dealer>(); list_td.Add(td); vm.text_dealer = list_td; list_vm = new List<Text_City>(); list_vm.Add(vm); t_dealer.TextDrive_City = list_vm; list.Add(t_dealer); } else { if (exist_city) { //第一次添加城市跟特约店 vm = new Text_City(); vm.CityID = row["CITY_ID"].ToString(); vm.CityName = row["CITY_NAME"].ToString(); Text_dealer td = new Text_dealer(); td.DealerID = row["DEALER_ID"].ToString(); td.DealerName = row["DEALER_NAME"].ToString(); List<Text_dealer> list_td = new List<Text_dealer>(); list_td.Add(td); vm.text_dealer = list_td; t_dealer.TextDrive_City.Add(vm); } else { //已有城市,添加特约店 //Text_City vm = new Text_City(); Text_dealer td = new Text_dealer(); td.DealerID = row["DEALER_ID"].ToString(); td.DealerName = row["DEALER_NAME"].ToString(); vm.text_dealer.Add(td); //t_dealer.TextDrive_City.Find().text_dealer=; } } } return list; }