一、json文件内容如下,(小程序里好像有用到...):
二、读取包含省份城市区域的json文件,并整理成想要的结果:
string path = Server.MapPath("/js");
string file = System.IO.Path.Combine(path, "数据.json");
string message = "";
string fielval = readfile(file, ref message);
if(message=="")
{
fielval = fielval.Replace("\n", "").Replace("\t", "").Replace(" ", "");
JObject json=JObject.Parse(fielval);
string data = json["data"].ToString();
string namesel = "福建省";
Dictionary<string, List<string>> res = new Dictionary<string, List<string>>();
bool isget = getChild(namesel,"福州市", data,1, ref res);//下面有调用说明
message = "";
}
三、循环整理数据,计算出想要的结果:
/// <summary>
/// 循环整理数据
/// </summary>
/// <param name="sfname">省份</param>
/// <param name="cityname">城市</param>
/// <param name="children">json值</param>
/// <param name="ift">第几次循环</param>
/// <param name="res">返回</param>
/// <returns></returns>
private bool getChild(string sfname,string cityname, string children,int ift,ref Dictionary<string, List<string>> res)
{
try
{
List<Dictionary<string, object>> list = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(children);
if(ift==1 && !string.IsNullOrEmpty(sfname))
{
//saix 省份
var reslst = from u in list where u["name"].ToString() == "" + sfname + "" select u;
list = reslst.ToList();
}
if(ift==2 && !string.IsNullOrEmpty(cityname))
{
//赛选城市
var reslst = from u in list where u["name"].ToString() == "" + cityname + "" select u;
list = reslst.ToList();
}
if (list.Count > 0)
{
ift++;
List<string> dic_child = new List<string>();
for (int i = 0; i < list.Count; i++)
{
bool getcl = false;
string name = list[i]["name"].ToString().Trim();
if (list[i]["children"]!=null)
{
children = list[i]["children"].ToString().Trim();
if (children.Trim().ToLower() != "null" && children.Trim().ToLower() != "")
{
getcl = true;
getChild(name, cityname, children, ift, ref res);
}
}
else { children = ""; }
if(!getcl)
{
dic_child.Add(name);//, children
}
}
if(ift==1 || !string.IsNullOrEmpty(sfname))
{
res.Add(sfname, dic_child);
}
else
{
res.Add(cityname, dic_child);
}
}
return true;
}
catch (Exception ex)
{
return false;
}
}
四、getChild(string sfname,string cityname, string children,int ift,ref Dictionary<string, List<string>> res),调用说明
bool isget = getChild("福建省","福州市", data,1, ref res);//
当sfname、cityname都有传值,相当于查询cityname下的区域信息,结果如下:
bool isget = getChild("福建省","", data,1, ref res);//
当只有sfname都有传值,而cityname为空,相当于查询sfname下所有城市及各城市下所有区域信息,结果如下:
五、readfile 方法:
public string readfile(string filename, ref string message)
{
string fielval = "";
try
{
if (System.IO.File.Exists(filename))
{
using (StreamReader sreader = new StreamReader(filename, Encoding.UTF8))
{
fielval = sreader.ReadToEnd();
sreader.Close();
sreader.Dispose();
}
}
else
{
message = "未找到文件" + filename;
}
}
catch (Exception ex)
{
message = ex.Message;
}
return fielval;
}