C#中如何将List<自定义>转为Json格式 及相关函数-DataContractJsonSerializer

对C#和.net使用List<自定义>和Json格式相互转化的方法进行总结

关于JSON的入门介绍见http://www.json.org/ ,或者百度,这里不赘述,不过通过下面的例子会有个更快捷和更直观的认识。

如Json格式[{"id":"1","name":"sara"},{"id":"2","name":"sara2"}]

自定义数据类型,用于List<>:

 [DataContract]
    class Person {
        [DataMember]
        public int id;
        [DataMember]
        public string name;
    }

程序中使用:

首先加入引用:

using System.Runtime.Serialization.Json;

using System.Runtime.Serialization;

using System.Text;

代码内容:

class Program
    {
        static void Main(string[] args)
        {
            //Product.GetAllSmartPhones();
            List<Person> nums = new List<Person>();
            nums.Add(new Person() {
                id=1,
                name="sara"
            });
            nums.Add(new Person() {
                id=1,
                name="sylar"
            });

            DataContractJsonSerializer json = new DataContractJsonSerializer(nums.GetType());

            string szJson = "";

            //序列化

            using (MemoryStream stream = new MemoryStream())
            {

                json.WriteObject(stream, nums);

                szJson = Encoding.UTF8.GetString(stream.ToArray());

            }
            Console.WriteLine(szJson);
            Console.ReadLine();
        }
    }

工程化时,可以对自定义数据结构重新定义一个类:

如:

public class TestListResult<T> : List<T>

{

public TestListResult()

{

this.Successed = false;

this.Message = "";

}

public bool Successed { get; set; }

public string Message { get; set; }

}

使用时同上在一个文件里一样

理解了以上原理,可以使用以下函数在项目中使用:

List<T>转Json

public static string Obj2Json<T>(T data)
{
    try
    {
        System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(data.GetType());
        using (MemoryStream ms = new MemoryStream())
        {
            serializer.WriteObject(ms, data);
            return Encoding.UTF8.GetString(ms.ToArray());
        }
    }
    catch
    {
        return null;
    }
}

Json转List<T>

public static Object Json2Obj(String json,Type t)
{
    try
    {
        System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(t);
        using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
        {

            return  serializer.ReadObject(ms);
        }
    }
    catch
    {
        return null;
    }
}

DataTable 转Json

public static string DataTable2Json(DataTable dt)
{
    if (dt.Rows.Count == 0)
    {
        return "";
    }

    StringBuilder jsonBuilder = new StringBuilder();
    // jsonBuilder.Append("{");
    //jsonBuilder.Append(dt.TableName.ToString());
    jsonBuilder.Append("[");//转换成多个model的形式
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        jsonBuilder.Append("{");
        for (int j = 0; j < dt.Columns.Count; j++)
        {
            jsonBuilder.Append("\"");
            jsonBuilder.Append(dt.Columns[j].ColumnName);
            jsonBuilder.Append("\":\"");
            jsonBuilder.Append(dt.Rows[i][j].ToString());
            jsonBuilder.Append("\",");
        }
        jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
        jsonBuilder.Append("},");
    }
    jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
    jsonBuilder.Append("]");
    //  jsonBuilder.Append("}");
    return jsonBuilder.ToString();
}

单个对象转JSON

public static T Json2Obj<T>(string json)
{
    T obj = Activator.CreateInstance<T>();
    using (System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)))
    {
        System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
        return (T)serializer.ReadObject(ms);
    }
}

将函数封装成类,更便于项目中引用:

 public class JsonHelper
    {
        /// <summary>
        /// 生成Json格式
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string GetJson<T>(T obj)
        {
            DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType());
            using (MemoryStream stream = new MemoryStream())
            {
                json.WriteObject(stream, obj);
                string szJson = Encoding.UTF8.GetString(stream.ToArray());
                return szJson;
            }
        }
        /// <summary>
        /// 获取Json的Model
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="szJson"></param>
        /// <returns></returns>
        public static T ParseFromJson<T>(string szJson)
        {
            T obj = Activator.CreateInstance<T>();
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                return (T)serializer.ReadObject(ms);
            }
        }
    }
 /// <summary>
        /// 反回JSON数据到前台
        /// </summary>
        /// <param name="dt">数据表</param>
        /// <returns>JSON字符串</returns>
        public string DataTableToJson(DataTable dt)
        {
            StringBuilder JsonString = new StringBuilder();
            if (dt != null && dt.Rows.Count > 0)
            {
                JsonString.Append("{ ");
                JsonString.Append("\"TableInfo\":[ ");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    JsonString.Append("{ ");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (j < dt.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\",");
                        }
                        else if (j == dt.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"");
                        }
                    }
                    if (i == dt.Rows.Count - 1)
                    {
                        JsonString.Append("} ");
                    }
                    else
                    {
                        JsonString.Append("}, ");
                    }
                }
                JsonString.Append("]}");
                return JsonString.ToString();
            }
            else
            {
                return null;
            }
        }

表的转化Json类:

public static class JsonTableHelper
    {
        /// <summary>
        /// 返回对象序列化
        /// </summary>
        /// <param name="obj">源对象</param>
        /// <returns>json数据</returns>
        public static string ToJson(this object obj)
        {
            JavaScriptSerializer serialize = new JavaScriptSerializer();
            return serialize.Serialize(obj);
        }

        /// <summary>
        /// 控制深度
        /// </summary>
        /// <param name="obj">源对象</param>
        /// <param name="recursionDepth">深度</param>
        /// <returns>json数据</returns>
        public static string ToJson(this object obj, int recursionDepth)
        {
            JavaScriptSerializer serialize = new JavaScriptSerializer();
            serialize.RecursionLimit = recursionDepth;
            return serialize.Serialize(obj);
        }

        /// <summary>
        /// DataTable转为json
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <returns>json数据</returns>
        public static string ToJson(DataTable dt)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();

            int index = 0;
            foreach (DataRow dr in dt.Rows)
            {
                Dictionary<string, object> result = new Dictionary<string, object>();

                foreach (DataColumn dc in dt.Columns)
                {
                    result.Add(dc.ColumnName, dr[dc].ToString());
                }
                dic.Add(index.ToString(), result);
                index++;
            }
            return ToJson(dic);
        }
    }

在Asp.net中前后台Json数据的传递

一、前台产生Json数据传递给后台处理

前台生成Json数据要使用javascript和json.js。

json.js 下载地址:http://www.json.org/json.js

前台代码:

            var people = [{ "UserName": "t1", "PassWord": "111111", "Sex": "男" },{ "UserName": "t2", "PassWord": "222222", "Sex": "女" }];
            var url = "Default.aspx?people=" + escape(people.toJSONString());
            request.open("POST", url, true);
            request.onreadystatechange = updatePage;
            request.send(null);

后台处理代码:

同上面的转化原理一样,我们先建立一个json数据类,便于List<>中使用。

[DataContract]//序列化
public class TestObj
{
    [DataMember]
    public string UserName { get; set; }
     [DataMember]
    public string PassWord { get; set; }
     [DataMember]
    public string Sex { get; set; }

public TestObj(string u,string p,string s)
	{
        UserName = u;
        PassWord = p;
        Sex = s;
	}
}

对前台提交的Json数据相互转化函数

//json 序列化

    public static string ToJsJson(object item)
    {
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(item.GetType());
        using(MemoryStream ms=new MemoryStream())
        {
            serializer.WriteObject(ms, item);
            StringBuilder sb = new StringBuilder();
            sb.Append(Encoding.UTF8.GetString(ms.ToArray()));
            return sb.ToString();
        }
    }

    //反序列化

    public static T FromJsonTo<T>(string jsonString)
    {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
        using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
        {
            T jsonObject = (T)ser.ReadObject(ms);
            return jsonObject;
        }
    }

在后台代码中调用以上函数进行对数据people的处理:

 //获取json字符串
        string jsonStr = Request["people"];
        List<TestObj> obj = Json.FromJsonTo<List<TestObj>>(jsonStr);
        foreach (TestObj item in obj)
            {
         Response.Write(string.Format("UserName:{0},Password:{1},Sex:{2}/r/n", item.UserName, item.PassWord, item.Sex));
            }
        Response.End();

最终的结果:

        List<TestObj> Users = new List<TestObj>();
        Users.Add(new TestObj("t1", "1", "男"));
        Users.Add(new TestObj("t2", "2", "女"));
        string json = Json.ToJsJson(Users);
        Response.Write(json);
        Response.End();

二、前台获取后台提交的Json数据

后台产生Json数据的方法如上原理中提到的:

 string Json;
       DataContractJsonSerializer json = new DataContractJsonSerializer(list.GetType());
                using (MemoryStream stream = new MemoryStream())
                {
                    json.WriteObject(stream, list);
                     Json = Encoding.UTF8.GetString(stream.ToArray());

                }
        return Json;   
  /// <summary>
    /// Json的数据结构
    /// </summary>
    [DataContract]
    class ResultJson
    {
        [DataMember]
        public bool Result;
        [DataMember]
        public int Count;
        [DataMember]
        public string Message;
    }

前台获取后台返回的Json字符串:

  function updatePage() {
            if (request.readyState == 4) {
                if (request.status == 200) {
                    var response = request.responseText;
                    //转化成对象
                    //方法1
                        response = response.parseJSON();
                    //方法2
                    // response = eval("(" + response + ")");
                    //对象访问方式
                    document.getElementById("d1").innerHTML = response[1].Sex;
                    //直接输出
                   // document.getElementById("d1").innerHTML = response;
                }
            }
        }

复杂的Json字符串操作方法:

假如我们要转化的JSON字符串格式为:

{
    "encoding":"UTF-8",
    "plug-ins":["python","c++","ruby"],
    "indent":{
        "length":3,
        "use_space":true
    }
}

然后编写相应的序列化的类,注意下面Indent类加的属性:

[DataContract]
class Config
{
    [DataMember(Order = 0)]
    public string encoding { get; set; }
    [DataMember(Order = 1)]
    public string[] plugins { get; set; }
    [DataMember(Order = 2)]
    public Indent indent { get; set; }
}

[DataContract]
class Indent
{
    [DataMember(Order = 0)]
    public int length { get; set; }
    [DataMember(Order = 1)]
    public bool use_space { get; set; }
}

输出JSON字符串

var config = new Config(){
                         encoding = "UTF-8",
                         plugins = new string[]{"python", "C++", "C#"},
                         indent = new Indent(){ length = 4, use_space = false}
                         };
var serializer = new DataContractJsonSerializer(typeof(Config));
var stream = new MemoryStream();
serializer.WriteObject(stream, config);

byte[] dataBytes = new byte[stream.Length];

stream.Position = 0;

stream.Read(dataBytes, 0, (int)stream.Length);

string dataString = Encoding.UTF8.GetString(dataBytes);

Console.WriteLine("JSON string is:");
Console.WriteLine(dataString);

结果:

JSON string is:
{"encoding":"UTF-8","plugins":["python","C++","C#"],"indent":{"length":4,"use_space":false}}

读取Json字符串内容:

var mStream = new MemoryStream(Encoding.Default.GetBytes(dataString));
Config readConfig = (Config)serializer.ReadObject(mStream);

Console.WriteLine("Encoding is: {0}", readConfig.encoding);
foreach (string plugin in readConfig.plugins)
{
    Console.WriteLine("plugins is: {0}", plugin);
}
Console.WriteLine("indent.length is: {0}", readConfig.indent.length);
Console.WriteLine("indent.use_space is: {0}", readConfig.indent.use_space);

结果:

Encoding is: UTF-8
plugins is: python
plugins is: C++
plugins is: C#
indent.length is: 4
indent.use_space is: False

时间: 2024-10-06 14:57:35

C#中如何将List<自定义>转为Json格式 及相关函数-DataContractJsonSerializer的相关文章

C#中怎样将List&amp;lt;自己定义&amp;gt;转为Json格式 及相关函数-DataContractJsonSerializer

对C#和.net使用List<自己定义>和Json格式相互转化的方法进行总结 关于JSON的入门介绍见http://www.json.org/ ,或者百度,这里不赘述,只是通过以下的样例会有个更快捷和更直观的认识. 如Json格式[{"id":"1","name":"sara"},{"id":"2","name":"sara2"}] 自

关于多条数据转为json格式单次传输的问题 2017.05.27

数据形式如下: var mycars = [];//定义数组存放多条数据 for(var i=0;i<2;i++){ var jsonData = {};//定义变量存放单条数据 jsonData.MainCmdID = 1; jsonData.SubCmdID = i; mycars[i]=JSON.stringify(jsonData);//单挑数据转为json格式,存放到数组 } var toStr="";//定义字符变量准备拼接json for (var i=0;i<

ios 中 数组、字典转成json格式上传到后台,遇到的问题

项目需求需要传json格式到后台 字典转成JSON p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; color: #000000 } p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; color: #000000; min-height: 21.0px } p.p3 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0

前后端分离,转json格式问题

json格式是字符串形式,将数据库中的数据取出来转为json格式时,要将小数等数据转位字符串(str方法) 报错类型: 1,decimal(5,2)  表示5位数,其中小数有两位,decimal要转为str类型 原文地址:https://www.cnblogs.com/wjun0/p/11526727.html

POST JSON (字典 自定义类转为JSON上传)

/// POST JSON 的主方法 主要设置  Content-Type 为  application/json 剩下就是将 类转为JSON 格式二进制数 - (void)postJSON:(NSData *)data { // 1. url NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/postjson.php"]; // 2. request NSMutableURLRequest *request = [NSMutab

python里如何将字典转为json字符串

在Pyhton里有一个叫simplejson的库可以方便的将完成对json的生成与解析.这个包里主要有四个方法:dump和dumps由python数据类型生成json,load和loads将json解析成为python的数据类型. load和loads(解析JSON成Python的数据类型)dump和dumps的唯一区别是dump会生成一个类文件对象,dumps会生成字符串,同理load和loads分别解析类文件对象和字符串格式的JSON 在django的HttpResponse中的返回中需要将

DataTable转为JSON数据格式代码

public class DataTableConvertJson { #region dataTable转换成Json格式 /// <summary> /// dataTable转换成Json格式 /// </summary> /// <param name="dt"></param> /// <returns></returns> public static string DataTable2Json(Data

json格式在ruby和rails中的注意事项

#虚拟网络拓扑的json数据 def topodata #@vnic = Vnic.all #flash.now[:notice] = 'Message sent!' #flash.now[:alert] = 'Message sent!' simple_json = { nodes: [{ name: 'bob', age: "22", awesome: "true" }, { name: 'bob', age: 22, awesome:true }], link

.NET的JSON格式数据的三种转换方式

说明: 1..Net进行JSON格式的数据传递的时候,势必用到序列化和反序列化对象,总共有三种方式可是在.NET中实现序列化和反序列化的需求. 2.操作JSON的速度是:Json.net > MicrosoftJSON > JsJSON 3.下面对应的三种将对象转为JSON格式数据方式的目前相对很好博客. 5.谢谢各位前辈的辛苦发帖,各人表示由衷的敬意. JSON.NET 参考的博客: [1]JSON.NET使用技巧:http://www.cnblogs.com/IPrograming/p/4