首页 > 代码库 > C# DataSet转JSON

C# DataSet转JSON

  经常会遇到系统数据交互采用JSON数据格式进行交互的,避免不必要的重复工作,记录下自己的处理方式。

获取数据集之后,通过函数对数据集信息进行整理通过.Net Framework3.5提出的JavaScriptSerializer类进行DataSet数据的序列化,

需要添加System.Web.Extensions引用:

 private static string DataToJson(DataSet metaData,string msg)
        {            
            DataTable resultInfo = new DataTable("success");
            resultInfo.Columns.Add("RETURN_CODE", Type.GetType("System.String"));
            resultInfo.Columns.Add("ERROR_MSG", Type.GetType("System.String"));
            DataRow newRow = resultInfo.NewRow();
            if (metaData =http://www.mamicode.com/= null || metaData.Tables.Count <= 0 || metaData.Tables[0].Rows.Count <= 0)
            {
                newRow["RETURN_CODE"] = "-1";
                if (string.IsNullOrEmpty(msg))
                {
                    newRow["ERROR_MSG"] = "查询结果为空";
                }
                else
                {
                    newRow["ERROR_MSG"] = msg;
                }
                resultInfo.Rows.Add(newRow);
                metaData.Tables.Add(resultInfo);
            }
            else
            {
                newRow["RETURN_CODE"] = "0";
                newRow["ERROR_MSG"] = "";
                resultInfo.Rows.Add(newRow);
                metaData.Tables.Add(resultInfo);
            }
            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            foreach (DataTable dt in metaData.Tables)
            {
                sb.Append(string.Format("\"{0}\":",dt.TableName));
                ArrayList arrayList=new ArrayList();
                foreach (DataRow dataRow in dt.Rows)
                {
                    Dictionary<string, object> dictionary = new Dictionary<string, object>();
                    foreach (DataColumn dataColumn in dt.Columns)
                    {
                        dictionary.Add(dataColumn.ColumnName,dataRow[dataColumn.ColumnName]);
                    }
                    arrayList.Add(dictionary);
                }
                sb.Append(serializer.Serialize(arrayList));
                sb.Append(",");
            }
            return sb.Remove(sb.Length - 1, 1).Append("}").ToString();
        }

   此时我们获取了一个JSON格式的字符串,在接收方同样可以通过JavaScriptSerializer将字符串转换为自己需要的数据格式如ArrayList:

        private ArrayList JsonToList(string json)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            Dictionary<string,object> dictionary= serializer.Deserialize<Dictionary<string,object>>(json);
            return (ArrayList)dictionary["data"];
        }

      也可以将JSON转换为对象:

 

internal bool ValidateWebJsonValues(ref UserInfo userInfo, string userName, string passWord)
        {
            try
            {
                string json = "{"data":{"accounts":null,"delFlag":"0","email":null,"emailState":null,"instOrgId":null,"institue":false,"member":false,"mobile":null,"org":false,"realName":"包文强","state":"0","teacher":true,"userId":121438653944262,"userType":"2"},"success":true}";

                JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
                Dictionary<string, object> dic = jsSerializer.Deserialize<Dictionary<string, object>>(json);
                bool dataResult = (bool)dic["success"];
                if (dataResult)
                {
                    Dictionary<string, object> dataDic = (Dictionary<string, object>)dic["data"];
                    Type type = typeof(UserInfo);
                    PropertyInfo[] propInfo = type.GetProperties();
                    foreach (PropertyInfo prop in propInfo)
                    {
                        if (dataDic[prop.Name] != null)
                        {
                            prop.SetValue(userInfo, dataDic[prop.Name], null);
                        }
                        else
                        {
                            prop.SetValue(userInfo, "", null);
                        }
                    }
                }
                return dataResult;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

以上代码是根据个人过往处理这方面问题的代码进行简单调整,也涉及到一些判断逻辑。作为参考,可以修改调整后使用。

C# DataSet转JSON