然后在其属性上添加JsonProperty美高梅赌堵59599,别的controller我们暂用不到

2019-11-07 作者:联系我们   |   浏览(102)

C# 转换Json类,

 

 

美高梅赌堵59599 1

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Reflection;
using System.Collections;
using System.Data.Common;

namespace DotNet.Utilities
{
    //JSON转换类
    public class ConvertJson
    {
        #region 私有方法
        /// <summary>
        /// 过滤特殊字符
        /// </summary>
        private static string String2Json(String s)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                char c = s.ToCharArray()[i];
                switch (c)
                {
                    case '"':
                        sb.Append("\""); break;
                    case '\':
                        sb.Append("\\"); break;
                    case '/':
                        sb.Append("\/"); break;
                    case 'b':
                        sb.Append("\b"); break;
                    case 'f':
                        sb.Append("\f"); break;
                    case 'n':
                        sb.Append("\n"); break;
                    case 'r':
                        sb.Append("\r"); break;
                    case 't':
                        sb.Append("\t"); break;
                    default:
                        sb.Append(c); break;
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// 格式化字符型、日期型、布尔型
        /// </summary>
        private static string StringFormat(string str, Type type)
        {
            if (type == typeof(string))
            {
                str = String2Json(str);
                str = """ + str + """;
            }
            else if (type == typeof(DateTime))
            {
                str = """ + str + """;
            }
            else if (type == typeof(bool))
            {
                str = str.ToLower();
            }
            else if (type != typeof(string) && string.IsNullOrEmpty(str))
            {
                str = """ + str + """;
            }
            return str;
        }
        #endregion

        #region List转换成Json
        /// <summary>
        /// List转换成Json
        /// </summary>
        public static string ListToJson<T>(IList<T> list)
        {
            object obj = list[0];
            return ListToJson<T>(list, obj.GetType().Name);
        }

        /// <summary>
        /// List转换成Json 
        /// </summary>
        public static string ListToJson<T>(IList<T> list, string jsonName)
        {
            StringBuilder Json = new StringBuilder();
            if (string.IsNullOrEmpty(jsonName)) jsonName = list[0].GetType().Name;
            Json.Append("{"" + jsonName + "":[");
            if (list.Count > 0)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    T obj = Activator.CreateInstance<T>();
                    PropertyInfo[] pi = obj.GetType().GetProperties();
                    Json.Append("{");
                    for (int j = 0; j < pi.Length; j++)
                    {
                        Type type = pi[j].GetValue(list[i], null).GetType();
                        Json.Append(""" + pi[j].Name.ToString() + "":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));

                        if (j < pi.Length - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < list.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]}");
            return Json.ToString();
        }
        #endregion

        #region 对象转换为Json
        /// <summary> 
        /// 对象转换为Json 
        /// </summary> 
        /// <param name="jsonObject">对象</param> 
        /// <returns>Json字符串</returns> 
        public static string ToJson(object jsonObject)
        {
            string jsonString = "{";
            PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties();
            for (int i = 0; i < propertyInfo.Length; i++)
            {
                object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);
                string value = string.Empty;
                if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan)
                {
                    value = "'" + objectValue.ToString() + "'";
                }
                else if (objectValue is string)
                {
                    value = "'" + ToJson(objectValue.ToString()) + "'";
                }
                else if (objectValue is IEnumerable)
                {
                    value = ToJson((IEnumerable)objectValue);
                }
                else
                {
                    value = ToJson(objectValue.ToString());
                }
                jsonString += """ + ToJson(propertyInfo[i].Name) + "":" + value + ",";
            }
            jsonString.Remove(jsonString.Length - 1, jsonString.Length);
            return jsonString + "}";
        }
        #endregion

        #region 对象集合转换Json
        /// <summary> 
        /// 对象集合转换Json 
        /// </summary> 
        /// <param name="array">集合对象</param> 
        /// <returns>Json字符串</returns> 
        public static string ToJson(IEnumerable array)
        {
            string jsonString = "[";
            foreach (object item in array)
            {
                jsonString += ToJson(item) + ",";
            }
            jsonString.Remove(jsonString.Length - 1, jsonString.Length);
            return jsonString + "]";
        }
        #endregion

        #region 普通集合转换Json
        /// <summary> 
        /// 普通集合转换Json 
        /// </summary> 
        /// <param name="array">集合对象</param> 
        /// <returns>Json字符串</returns> 
        public static string ToArrayString(IEnumerable array)
        {
            string jsonString = "[";
            foreach (object item in array)
            {
                jsonString = ToJson(item.ToString()) + ",";
            }
            jsonString.Remove(jsonString.Length - 1, jsonString.Length);
            return jsonString + "]";
        }
        #endregion

        #region  DataSet转换为Json
        /// <summary> 
        /// DataSet转换为Json 
        /// </summary> 
        /// <param name="dataSet">DataSet对象</param> 
        /// <returns>Json字符串</returns> 
        public static string ToJson(DataSet dataSet)
        {
            string jsonString = "{";
            foreach (DataTable table in dataSet.Tables)
            {
                jsonString += """ + table.TableName + "":" + ToJson(table) + ",";
            }
            jsonString = jsonString.TrimEnd(',');
            return jsonString + "}";
        }
        #endregion

        #region Datatable转换为Json
        /// <summary> 
        /// Datatable转换为Json 
        /// </summary> 
        /// <param name="table">Datatable对象</param> 
        /// <returns>Json字符串</returns> 
        public static string ToJson(DataTable dt)
        {
            StringBuilder jsonString = new StringBuilder();
            jsonString.Append("[");
            DataRowCollection drc = dt.Rows;
            for (int i = 0; i < drc.Count; i++)
            {
                jsonString.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string strKey = dt.Columns[j].ColumnName;
                    string strValue = drc[i][j].ToString();
                    Type type = dt.Columns[j].DataType;
                    jsonString.Append(""" + strKey + "":");
                    strValue = StringFormat(strValue, type);
                    if (j < dt.Columns.Count - 1)
                    {
                        jsonString.Append(strValue + ",");
                    }
                    else
                    {
                        jsonString.Append(strValue);
                    }
                }
                jsonString.Append("},");
            }
            jsonString.Remove(jsonString.Length - 1, 1);
            jsonString.Append("]");
            return jsonString.ToString();
        }

        /// <summary>
        /// DataTable转换为Json 
        /// </summary>
        public static string ToJson(DataTable dt, string jsonName)
        {
            StringBuilder Json = new StringBuilder();
            if (string.IsNullOrEmpty(jsonName)) jsonName = dt.TableName;
            Json.Append("{"" + jsonName + "":[");
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Json.Append("{");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        Type type = dt.Rows[i][j].GetType();
                        Json.Append(""" + dt.Columns[j].ColumnName.ToString() + "":" + StringFormat(dt.Rows[i][j].ToString(), type));
                        if (j < dt.Columns.Count - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < dt.Rows.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]}");
            return Json.ToString();
        }
        #endregion

        #region DataReader转换为Json
        /// <summary> 
        /// DataReader转换为Json 
        /// </summary> 
        /// <param name="dataReader">DataReader对象</param> 
        /// <returns>Json字符串</returns> 
        public static string ToJson(DbDataReader dataReader)
        {
            StringBuilder jsonString = new StringBuilder();
            jsonString.Append("[");
            while (dataReader.Read())
            {
                jsonString.Append("{");
                for (int i = 0; i < dataReader.FieldCount; i++)
                {
                    Type type = dataReader.GetFieldType(i);
                    string strKey = dataReader.GetName(i);
                    string strValue = dataReader[i].ToString();
                    jsonString.Append(""" + strKey + "":");
                    strValue = StringFormat(strValue, type);
                    if (i < dataReader.FieldCount - 1)
                    {
                        jsonString.Append(strValue + ",");
                    }
                    else
                    {
                        jsonString.Append(strValue);
                    }
                }
                jsonString.Append("},");
            }
            dataReader.Close();
            jsonString.Remove(jsonString.Length - 1, 1);
            jsonString.Append("]");
            return jsonString.ToString();
        }
        #endregion
    }
}

ConvertJson

 

转换Json类, using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Reflection; using System.Collections; using System.Data.Commo...

一、JSON使用JsonPropertyAttribute重命名属性名

1.先创建一个Movie对象,然后在其属性上添加JsonProperty,并指定重命名的名称。注意:属性Name和Director已指定。

[csharp] view plain copy

 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using GongHuiNewtonsoft.Json;  
  6.   
  7. namespace JSONDemo  
  8. {      
  9.     public class Movie  
  10.     {  
  11.         [JsonProperty("name")]  
  12.         public string Name { get; set; }  
  13.   
  14.         [JsonProperty("Chinese Director")]  
  15.         public string Director { get; set; }  
  16.           
  17.         public int ReleaseYear { get; set; }  
  18.     }  
  19. }  

2.实例化Movie对象,然后序列化。

[csharp] view plain copy

 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Data;  
  6. using GongHuiNewtonsoft.Json;  
  7. using GongHuiNewtonsoft.Json.Serialization;  
  8. using GongHuiNewtonsoft.Json.Converters;  
  9.   
  10. namespace JSONDemo  
  11. {  
  12.     class Program  
  13.     {  
  14.         static void Main(string[] args)  
  15.         {  
  16.             Movie m = new Movie  
  17.             {  
  18.                 Name = "非诚勿扰1",  
  19.                 Director = "冯小刚",  
  20.                 ReleaseYear = 2008  
  21.             };  
  22.   
  23.             string json = JsonConvert.SerializeObject(m, Formatting.Indented);  
  24.             Console.WriteLine(json);  
  25.         }  
  26.     }  
  27. }  

3.运行结果,注意:属性ReleaseYear未被重命名。

美高梅赌堵59599 2

 

c#实现list,dataset,DataTable转换成josn等各种转换方法总和,

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Reflection;
using System.Collections;
using System.Data.Common;

namespace DotNet.Utilities
{
    //JSON转换类
    public class ConvertJson
    {
        #region 私有方法
        /// <summary>
        /// 过滤特殊字符
        /// </summary>
        private static string String2Json(String s)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                char c = s.ToCharArray()[i];
                switch (c)
                {
                    case '"':
                        sb.Append("\""); break;
                    case '\':
                        sb.Append("\\"); break;
                    case '/':
                        sb.Append("\/"); break;
                    case 'b':
                        sb.Append("\b"); break;
                    case 'f':
                        sb.Append("\f"); break;
                    case 'n':
                        sb.Append("\n"); break;
                    case 'r':
                        sb.Append("\r"); break;
                    case 't':
                        sb.Append("\t"); break;
                    default:
                        sb.Append(c); break;
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// 格式化字符型、日期型、布尔型
        /// </summary>
        private static string StringFormat(string str, Type type)
        {
            if (type == typeof(string))
            {
                str = String2Json(str);
                str = """ + str + """;
            }
            else if (type == typeof(DateTime))
            {
                str = """ + str + """;
            }
            else if (type == typeof(bool))
            {
                str = str.ToLower();
            }
            else if (type != typeof(string) && string.IsNullOrEmpty(str))
            {
                str = """ + str + """;
            }
            return str;
        }
        #endregion

        #region List转换成Json
        /// <summary>
        /// List转换成Json
        /// </summary>
        public static string ListToJson<T>(IList<T> list)
        {
            object obj = list[0];
            return ListToJson<T>(list, obj.GetType().Name);
        }

        /// <summary>
        /// List转换成Json
        /// </summary>
        public static string ListToJson<T>(IList<T> list, string jsonName)
        {
            StringBuilder Json = new StringBuilder();
            if (string.IsNullOrEmpty(jsonName)) jsonName = list[0].GetType().Name;
            Json.Append("{"" + jsonName + "":[");
            if (list.Count > 0)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    T obj = Activator.CreateInstance<T>();
                    PropertyInfo[] pi = obj.GetType().GetProperties();
                    Json.Append("{");
                    for (int j = 0; j < pi.Length; j++)
                    {
                        Type type = pi[j].GetValue(list[i], null).GetType();
                        Json.Append(""" + pi[j].Name.ToString() + "":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));

                        if (j < pi.Length - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < list.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]}");
            return Json.ToString();
        }
        #endregion

        #region 对象转换为Json
        /// <summary>
        /// 对象转换为Json
        /// </summary>
        /// <param name="jsonObject">对象</param>
        /// <returns>Json字符串</returns>
        public static string ToJson(object jsonObject)
        {
            string jsonString = "{";
            PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties();
            for (int i = 0; i < propertyInfo.Length; i++)
            {
                object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);
                string value = string.Empty;
                if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan)
                {
                    value = "'" + objectValue.ToString() + "'";
                }
                else if (objectValue is string)
                {
                    value = "'" + ToJson(objectValue.ToString()) + "'";
                }
                else if (objectValue is IEnumerable)
                {
                    value = ToJson((IEnumerable)objectValue);
                }
                else
                {
                    value = ToJson(objectValue.ToString());
                }
                jsonString += """ + ToJson(propertyInfo[i].Name) + "":" + value + ",";
            }
            jsonString.Remove(jsonString.Length - 1, jsonString.Length);
            return jsonString + "}";
        }
        #endregion

        #region 对象集合转换Json
        /// <summary>
        /// 对象集合转换Json
        /// </summary>
        /// <param name="array">集合对象</param>
        /// <returns>Json字符串</returns>
        public static string ToJson(IEnumerable array)
        {
            string jsonString = "[";
            foreach (object item in array)
            {
                jsonString += ToJson(item) + ",";
            }
            jsonString.Remove(jsonString.Length - 1, jsonString.Length);
            return jsonString + "]";
        }
        #endregion

        #region 普通集合转换Json
        /// <summary>
        /// 普通集合转换Json
        /// </summary>
        /// <param name="array">集合对象</param>
        /// <returns>Json字符串</returns>
        public static string ToArrayString(IEnumerable array)
        {
            string jsonString = "[";
            foreach (object item in array)
            {
                jsonString = ToJson(item.ToString()) + ",";
            }
            jsonString.Remove(jsonString.Length - 1, jsonString.Length);
            return jsonString + "]";
        }
        #endregion

        #region  DataSet转换为Json
        /// <summary>
        /// DataSet转换为Json
        /// </summary>
        /// <param name="dataSet">DataSet对象</param>
        /// <returns>Json字符串</returns>
        public static string ToJson(DataSet dataSet)
        {
            string jsonString = "{";
            foreach (DataTable table in dataSet.Tables)
            {
                jsonString += """ + table.TableName + "":" + ToJson(table) + ",";
            }
            jsonString = jsonString.TrimEnd(',');
            return jsonString + "}";
        }
        #endregion

        #region Datatable转换为Json
        /// <summary>
        /// Datatable转换为Json
        /// </summary>
        /// <param name="table">Datatable对象</param>
        /// <returns>Json字符串</returns>
        public static string ToJson(DataTable dt)
        {
            StringBuilder jsonString = new StringBuilder();
            jsonString.Append("[");
            DataRowCollection drc = dt.Rows;
            for (int i = 0; i < drc.Count; i++)
            {
                jsonString.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string strKey = dt.Columns[j].ColumnName;
                    string strValue = drc[i][j].ToString();
                    Type type = dt.Columns[j].DataType;
                    jsonString.Append(""" + strKey + "":");
                    strValue = StringFormat(strValue, type);
                    if (j < dt.Columns.Count - 1)
                    {
                        jsonString.Append(strValue + ",");
                    }
                    else
                    {
                        jsonString.Append(strValue);
                    }
                }
                jsonString.Append("},");
            }
            jsonString.Remove(jsonString.Length - 1, 1);
            jsonString.Append("]");
            return jsonString.ToString();
        }

        /// <summary>
        /// DataTable转换为Json
        /// </summary>
        public static string ToJson(DataTable dt, string jsonName)
        {
            StringBuilder Json = new StringBuilder();
            if (string.IsNullOrEmpty(jsonName)) jsonName = dt.TableName;
            Json.Append("{"" + jsonName + "":[");
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Json.Append("{");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        Type type = dt.Rows[i][j].GetType();
                        Json.Append(""" + dt.Columns[j].ColumnName.ToString() + "":" + StringFormat(dt.Rows[i][j].ToString(), type));
                        if (j < dt.Columns.Count - 1)
                        {
                            Json.Append(",");
                        }
                    }
                    Json.Append("}");
                    if (i < dt.Rows.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]}");
            return Json.ToString();
        }
        #endregion

        #region DataTable转换为Json
        /// <summary>
        /// DataReader转换为Json
        /// </summary>
        /// <param name="dataReader">DataReader对象</param>
        /// <returns>Json字符串</returns>
        public static string ToJson(DbDataReader dataReader)
        {
            StringBuilder jsonString = new StringBuilder();
            jsonString.Append("[");
            while (dataReader.Read())
            {
                jsonString.Append("{");
                for (int i = 0; i < dataReader.FieldCount; i++)
                {
                    Type type = dataReader.GetFieldType(i);
                    string strKey = dataReader.GetName(i);
                    string strValue = dataReader[i].ToString();
                    jsonString.Append(""" + strKey + "":");
                    strValue = StringFormat(strValue, type);
                    if (i < dataReader.FieldCount - 1)
                    {
                        jsonString.Append(strValue + ",");
                    }
                    else
                    {
                        jsonString.Append(strValue);
                    }
                }
                jsonString.Append("},");
            }
            dataReader.Close();
            jsonString.Remove(jsonString.Length - 1, 1);
            jsonString.Append("]");
            return jsonString.ToString();
        }
        #endregion
    }
}

using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Reflect...

将JSON转换成DataTable、DataSet或是List等,也有可能将DataTable、DataSet或是List转换成JSON的

Controller 这一层首先要添加对WCF 的引用:

二、JSON使用JsonPropertyAttribute序列化升序排序属性

1.先创建一个Movie对象,然后指定JsonProperty,并添加Order属性。

[csharp] view plain copy

 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using GongHuiNewtonsoft.Json;  
  6.   
  7. namespace JSONDemo  
  8. {      
  9.     public class Movie  
  10.     {  
  11.         [JsonProperty(Order=4)]  
  12.         public string Name { get; set; }  
  13.   
  14.         [JsonProperty(Order=0)]  
  15.         public string Director { get; set; }  
  16.           
  17.         public int ReleaseYear { get; set; }  
  18.   
  19.         [JsonProperty(Order=-3)]  
  20.         public string ChiefActor { get; set; }  
  21.   
  22.         [JsonProperty(Order=2)]  
  23.         public string ChiefActress { get; set; }  
  24.     }  
  25. }  

2.实例化Movie对象,然后序列化。

[csharp] view plain copy

 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Data;  
  6. using GongHuiNewtonsoft.Json;  
  7. using GongHuiNewtonsoft.Json.Serialization;  
  8. using GongHuiNewtonsoft.Json.Converters;  
  9.   
  10. namespace JSONDemo  
  11. {  
  12.     class Program  
  13.     {  
  14.         static void Main(string[] args)  
  15.         {  
  16.             Movie m = new Movie  
  17.             {  
  18.                 Name = "非诚勿扰1",  
  19.                 Director = "冯小刚",  
  20.                 ReleaseYear = 2008,  
  21.                 ChiefActor="葛优",  
  22.                 ChiefActress="舒淇"  
  23.             };  
  24.   
  25.             string json = JsonConvert.SerializeObject(m, Formatting.Indented);  
  26.             Console.WriteLine(json);  
  27.         }  
  28.     }  
  29. }  

3.运行结果。注意:未指定Order序号的属性,界定于大于负数小于正数,并按默认顺序排序。

美高梅赌堵59599 3

 

代码:

美高梅赌堵59599 4

三、JSON使用JsonPropertyAttribute反序列化属性时,Required指定属性性质

1.创建一个Movie对象,给属性添加JsonProperty,并指定其Required的性质。属性Name必须有值,DateTime可以为空.

[csharp] view plain copy

 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using GongHuiNewtonsoft.Json;  
  6.   
  7. namespace JSONDemo  
  8. {      
  9.     public class Movie  
  10.     {  
  11.         [JsonProperty(Required=Required.Always)]  
  12.         public string Name { get; set; }  
  13.   
  14.         [JsonProperty(Required = Required.AllowNull)]  
  15.         public DateTime? ReleaseDate { get; set; }  
  16.   
  17.         public string Director { get; set; }  
  18.     }  
  19. }  

2.实例化Movie对象,反序列化JSON。

[csharp] view plain copy

 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Data;  
  6. using GongHuiNewtonsoft.Json;  
  7. using GongHuiNewtonsoft.Json.Serialization;  
  8. using GongHuiNewtonsoft.Json.Converters;  
  9.   
  10. namespace JSONDemo  
  11. {  
  12.     class Program  
  13.     {  
  14.         static void Main(string[] args)  
  15.         {  
  16.             string json = @"{  
  17.                 'Name':'举起手来1',  
  18.                 'Director':'冯小宁',  
  19.                 'ReleaseDate':null  
  20.             }";  
  21.   
  22.             Movie m = JsonConvert.DeserializeObject<Movie>(json);  
  23.             Console.WriteLine(m.Name);  
  24.             Console.WriteLine(m.Director);  
  25.             Console.WriteLine(m.ReleaseDate);  
  26.         }  
  27.     }  
  28. }  

3.运行结果是

美高梅赌堵59599 5

 

1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Web;
  5 using System.Text;
  6 using System.Data;
  7 using System.Data.Common;
  8 using System.Collections;
  9 using System.Reflection;
10
11 namespace BJYX.WEB.Public
12 {
13     public class Creat_Json
14     {
15         public Creat_Json()
16         {
17             //
18             // TODO: 在此处添加构造函数逻辑
19             //
20         }
21  /// <summary>
        /// 将json转换为DataTable
        /// </summary>
        /// <param name="strJson">得到的json</param>
        /// <returns></returns>
        private DataTable JsonToDataTable(string strJson)
        {
            //转换json格式
            strJson = strJson.Replace(","", "*"").Replace("":", ""#").ToString();
            //取出表名  
            var rg = new Regex(@"(?<={)[^:]+(?=:[)", RegexOptions.IgnoreCase);
            string strName = rg.Match(strJson).Value;
            DataTable tb = null;
            //去除表名  
            strJson = strJson.Substring(strJson.IndexOf("[") + 1);
            strJson = strJson.Substring(0, strJson.IndexOf("]"));

 

四、JSON使用JsonPropertyAttribute序列化引用类型集合

1.创建一个Director对象,并声明一个本身类型的属性,指定JsonProperty中的IsReference为true.

[csharp] view plain copy

 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using GongHuiNewtonsoft.Json;  
  6.   
  7. namespace JSONDemo  
  8. {  
  9.     public class Director  
  10.     {  
  11.         public string Name { get; set; }  
  12.   
  13.         [JsonProperty(IsReference=true)]  
  14.         public Director ExecuteDir { get; set; }  
  15.     }  
  16. }  

 

2.创建一个Movie对象,声明一个Director集合的属性,指定JsonProperty中的IsReference为true.

[csharp] view plain copy

 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using GongHuiNewtonsoft.Json;  
  6.   
  7. namespace JSONDemo  
  8. {      
  9.     public class Movie  
  10.     {  
  11.         public string Name { get; set; }  
  12.   
  13.         [JsonProperty(ItemIsReference=true)]  
  14.         public IList<Director> Directors { get; set; }  
  15.     }  
  16. }  

3.序列化对象

[csharp] view plain copy

 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Data;  
  6. using GongHuiNewtonsoft.Json;  
  7. using GongHuiNewtonsoft.Json.Serialization;  
  8. using GongHuiNewtonsoft.Json.Converters;  
  9.   
  10. namespace JSONDemo  
  11. {  
  12.     class Program  
  13.     {  
  14.         static void Main(string[] args)  
  15.         {  
  16.             Director dir = new Director  
  17.             {  
  18.                 Name = "冯小刚"  
  19.             };  
  20.   
  21.             Director dir1 = new Director  
  22.             {  
  23.                 Name = "张艺谋",  
  24.                 ExecuteDir = dir  
  25.             };  
  26.   
  27.             Movie m = new Movie  
  28.             {  
  29.                 Name = "满城尽带黄金甲",  
  30.                 Directors = new List<Director>  
  31.                 {  
  32.                     dir,  
  33.                     dir1  
  34.                 }  
  35.             };  
  36.   
  37.             string json = JsonConvert.SerializeObject(m, Formatting.Indented);  
  38.             Console.WriteLine(json);  
  39.         }  
  40.     }  
  41. }  

4.运行结果

美高梅赌堵59599 6

 

            //获取数据  
            rg = new Regex(@"(?<={)[^}]+(?=})");
            MatchCollection mc = rg.Matches(strJson);
            for (int i = 0; i < mc.Count; i++)
            {
                string strRow = mc[i].Value;
                string[] strRows = strRow.Split('*');

如下,输入我们自己的wcf地址

五、JSON使用JsonPropertyAttribute序列化忽略属性null

1.创建一个Movie对象,并在属性上指定JsonProperty,添加NullValueHandling,忽略null

[csharp] view plain copy

 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using GongHuiNewtonsoft.Json;  
  6.   
  7. namespace JSONDemo  
  8. {      
  9.     public class Movie  
  10.     {  
  11.         public string Name { get; set; }  
  12.   
  13.         public string Director { get; set; }  
  14.   
  15.         [JsonProperty(NullValueHandling=NullValueHandling.Ignore)]  
  16.         public DateTime? LaunchDate { get; set; }  
  17.     }  
  18. }  

2.实例化对象Movie对象,然后序列化

[csharp] view plain copy

 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Data;  
  6. using GongHuiNewtonsoft.Json;  
  7. using GongHuiNewtonsoft.Json.Serialization;  
  8. using GongHuiNewtonsoft.Json.Converters;  
  9.   
  10. namespace JSONDemo  
  11. {  
  12.     class Program  
  13.     {  
  14.         static void Main(string[] args)  
  15.         {  
  16.             Movie m = new Movie  
  17.             {  
  18.                 Name = "爱情呼叫转移",  
  19.                 Director = "张建亚"  
  20.             };  
  21.   
  22.             string json = JsonConvert.SerializeObject(m, Formatting.Indented);  
  23.             Console.WriteLine(json);  
  24.         }  
  25.     }  
  26. }  

3.运行的结果

美高梅赌堵59599 7

 

JSON源代码下载地址:

原文链接:

                //创建表  
                if (tb == null)
                {
                    tb = new DataTable();
                    tb.TableName = strName;
                    foreach (string str in strRows)
                    {
                        var dc = new DataColumn();
                        string[] strCell = str.Split('#');

                        if (strCell[0].Substring(0, 1) == """)
                        {
                            int a = strCell[0].Length;
                            dc.ColumnName = strCell[0].Substring(1, a

 

  • 2);
                            }
                            else
                            {
                                dc.ColumnName = strCell[0];
                            }
                            tb.Columns.Add(dc);
                        }
                        tb.AcceptChanges();
                    }

为了解析嵌套结构的类,我们加入JsonBinder

                //增加内容  
                DataRow dr = tb.NewRow();
                for (int r = 0; r < strRows.Length; r++)
                {
                    dr[r] = strRows[r].Split('#')[1].Trim().Replace(",", ",").Replace(":", ":").Replace(""", "");
                }
                tb.Rows.Add(dr);
                tb.AcceptChanges();
            }

using System;

            return tb;
        }
22         public static string DataTable2Json(System.Data.DataTable dt)
23         {
24             System.Text.StringBuilder jsonBuilder = new System.Text.StringBuilder();
25             jsonBuilder.Append("{");
26             jsonBuilder.AppendFormat(""total":{0}, ", dt.Rows.Count);
27             jsonBuilder.Append(""rows":[ ");
28             for (int i = 0; i < dt.Rows.Count; i++)
29             {
30                 jsonBuilder.Append("{");
31                 for (int j = 0; j < dt.Columns.Count; j++)
32                 {
33                     jsonBuilder.Append(""");
34                     jsonBuilder.Append(dt.Columns[j].ColumnName);
35                     jsonBuilder.Append("":"");
36                     jsonBuilder.Append(dt.Rows[i][j].ToString().Replace("\", "\\").Replace("'", "'").Replace("t", " ").Replace("r", " ").Replace("n", "<br/>").Replace(""", """));
37                     jsonBuilder.Append("",");
38                 }
39                 jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
40                 jsonBuilder.Append("},");
41             }
42             jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
43             jsonBuilder.Append("]");
44             jsonBuilder.Append("}");
45             return jsonBuilder.ToString();
46         }
47         public static string DataTable2Json(System.Data.DataTable dt, int count)
48         {
49             System.Text.StringBuilder jsonBuilder = new System.Text.StringBuilder();
50             jsonBuilder.Append("{");
51             jsonBuilder.AppendFormat(""total":{0}, ", count);
52             jsonBuilder.Append(""rows":[ ");
53             for (int i = 0; i < dt.Rows.Count; i++)
54             {
55                 jsonBuilder.Append("{");
56                 for (int j = 0; j < dt.Columns.Count; j++)
57                 {
58                     jsonBuilder.Append(""");
59                     jsonBuilder.Append(dt.Columns[j].ColumnName);
60                     jsonBuilder.Append("":"");
61                     jsonBuilder.Append(dt.Rows[i][j].ToString().Replace("\", "\\

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Script.Serialization;

 

namespace InfoPub.Controllers

{

    public class JsonBinder<T> : IModelBinder

    {

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)

        {

            // 从䨮请?求¨®中D获?取¨?提¬¨¢交?的Ì?参?数ºy数ºy据Y

            var json = controllerContext.HttpContext.Request.Form[bindingContext.ModelName] as string;

 

            // 提¬¨¢交?参?数ºy是º?对?象¨®

            if (json.StartsWith("{") && json.EndsWith("}"))

本文由美高梅赌堵59599发布于联系我们,转载请注明出处:然后在其属性上添加JsonProperty美高梅赌堵59599,别的controller我们暂用不到

关键词: