懂Json的指点下,在asp.net 中如何将数据转换为标准的JSon格式数据

懂Json的指点下,在asp.net 中如何将数据转换为标准的JSon格式数据

问题描述:

我在asp.net 中前台调用 url: 'table_tree.ashx', 文件,在文件中生成了标准的Json格式字符串,但是前台还是读取不到,但是当我把获取的字符串保存到本地文件就能读取,这是什么原因,请指点,后台代码如下:

        context.Response.ContentType = "text/plain";
        StringBuilder str = new StringBuilder();
        Dictionary<string, string> myDictionary = new Dictionary<string, string>();
        str.Append("[");
        string sql = "SELECT   *  FROM   Depart order by PX" ;
        ds = db.executeQuery(sql);
        if (ds.Tables[0].Rows.Count > 0)
        {
            string tag = "";
            for (int i = 0; i < 1; i++)
            {
                str.Append(tag+"{\"SysID\":" + ds.Tables[0].Rows[i]["SysID"].ToString().Trim() + ",\"id\":" + ds.Tables[0].Rows[i]["id"].ToString().Trim() + ",\"pid\":" + ds.Tables[0].Rows[i]["pid"].ToString().Trim() + ",\"BMMC\":\"" + ds.Tables[0].Rows[i]["BMMC"].ToString().Trim() + "\"}");
                tag = ",";
            }
        }
        str.Append("]");
        context.Response.Write(str);

生成的字符串如下所示:
[{"SysID":D156A4C7-EA43-426B-ABEA-64E540C3148E,"id":B001,"pid":B,"BMMC":"缅甸达吉达项目部"},
{"SysID":6F03FE73-45BB-4178-A648-F0A3B44BDA3F,"id":A,"pid":0,"BMMC":"青岛总部"},
{"SysID":BAFF4EED-606D-4898-90B7-542EE325D40B,"id":A001,"pid":A,"BMMC":"班子"}]

用Newtonsoft.Json.dll转对象为json字符串好些,自己组合还得注意双引号的转义。题主的键值有问题,要用双引号扩起,这就是自己组合的弊端了。。字符串值一定要用引号扩起值,除非这个列是数字列,数字列如果允许为空还需要判断是否有值,要不直接+的话也会出现格式错误。用Newtonsoft.Json.dll类库会帮题主处理好

img

str.Append(tag+"{\"SysID\":\"" + ds.Tables[0].Rows[i]["SysID"].ToString().Trim() + "\",\"id\":\"" + ds.Tables[0].Rows[i]["id"].ToString().Trim() + "\",\"pid\":\"" + ds.Tables[0].Rows[i]["pid"].ToString().Trim() + "\",\"BMMC\":\"" + ds.Tables[0].Rows[i]["BMMC"].ToString().Trim() + "\"}");

有帮助麻烦点个采纳【本回答右上角】,谢谢~~有其他问题可以继续交流~