How to convert List (custom) to Json format and related functions in C #-DataContractJsonSerializer

Source: Internet
Author: User
Tags object serialization tojson

How to convert List (custom) to Json format and related functions in C #-DataContractJsonSerializer

Use List for C # And. net <自定义> And Json format conversion methods are summarized


For the introduction of JSON entry see http://www.json.org/, or Baidu, here not to go into details, but through the example below will have a faster and more intuitive understanding.

For example, in Json format [{"id": "1", "name": "sara" },{ "id": "2", "name": "sara2"}]

Custom Data Type, used for List <>:

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

Used in the program:

First add a reference:

using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.Text;
Code content:

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

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

            string szJson = "";

            //Serialization

            using (MemoryStream stream = new MemoryStream ())
            {

                json.WriteObject (stream, nums);

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

            }
            Console.WriteLine (szJson);
            Console.ReadLine ();
        }
    }
During engineering, you can redefine a class for a custom data structure:
Such as:

public class TestListResult: List
{
public TestListResult ()
{
this.Successed = false;
this.Message = "";
}
public bool Successed {get; set;}
public string Message {get; set;}
}

Use the same as above in a file

Understand the above principle, you can use the following functions in the project:

List to Json

public static string Obj2Json (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 to List
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 to 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 ("["); // Convert into multiple model form
    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 ();
}

Single object to JSON
public static T Json2Obj (string json)
{
    T obj = Activator.CreateInstance ();
    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);
    }
}

Encapsulate functions into classes for easier reference in projects:
 public class JsonHelper
    {
        ///

        /// Generate Json format
        ///
        ///
        ///
        ///
        public static string GetJson (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;
            }
        }
        ///

        /// Get Json's Model
        ///
        ///
        ///
        ///
        public static T ParseFromJson (string szJson)
        {
            T obj = Activator.CreateInstance ();
            using (MemoryStream ms = new MemoryStream (Encoding.UTF8.GetBytes (szJson)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer (obj.GetType ());
                return (T) serializer.ReadObject (ms);
            }
        }
    }
 ///

        /// Return JSON data to the foreground
        ///
        /// data sheet
        /// JSON string
        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;
            }
        }

The converted Json class of the table:
public static class JsonTableHelper
    {
        ///
 
        /// Return object serialization
        ///
        /// source object
        /// json data
        public static string ToJson (this object obj)
        {
            JavaScriptSerializer serialize = new JavaScriptSerializer ();
            return serialize.Serialize (obj);
        }

        ///
 
        /// control depth
        ///
        /// source object
        /// depth
        /// json data
        public static string ToJson (this object obj, int recursionDepth)
        {
            JavaScriptSerializer serialize = new JavaScriptSerializer ();
            serialize.RecursionLimit = recursionDepth;
            return serialize.Serialize (obj);
        }

        ///
 
        /// DataTable to json
        ///
        /// DataTable
        /// json data
        public static string ToJson (DataTable dt)
        {
            Dictionary dic = new Dictionary ();

            int index = 0;
            foreach (DataRow dr in dt.Rows)
            {
                Dictionary result = new Dictionary ();

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

Transfer of Json data in front and background in Asp.net
First, the Json data generated at the front desk is passed to the background processing

To generate Json data at the front desk, use javascript and json.js.

json.js: http://www.json.org/json.js


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

Background processing code:
The same as the above conversion principle, we first create a json data class for easy use in List <>.

[DataContract] // Serialization
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;
}
}

Mutual conversion function for Json data submitted by the front desk
// json serialization

    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 ();
        }
    }

    // deserialize

    public static T FromJsonTo (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;
        }
    }

Call the above function in the background code to process the data people:
 // Get json string
        string jsonStr = Request ["people"];
        List obj = Json.FromJsonTo> (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 ();

final result:
        List Users = new List ();
        Users.Add (new TestObj ("t1", "1", "Male"));
        Users.Add (new TestObj ("t2", "2", "Female"));
        string json = Json.ToJsJson (Users);
        Response.Write (json);
        Response.End ();

Second, the front desk obtains the Json data submitted by the background
The method of generating Json data in the background is as mentioned in the above principle:

 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;
  ///

    /// Json's data structure
    ///
    [DataContract]
    class ResultJson
    {
        [DataMember]
        public bool Result;
        [DataMember]
        public int Count;
        [DataMember]
        public string Message;
    }

The foreground gets the Json string returned by the background:

  function updatePage () {
            if (request.readyState == 4) {
                if (request.status == 200) {
                    var response = request.responseText;
                    // Convert to object
                    //method 1
                        response = response.parseJSON ();
                    // Method 2
                    // response = eval ("(" + response + ")");
                    // Object access method
                    document.getElementById ("d1"). innerHTML = response [1] .Sex;
                    // Direct output
                   // document.getElementById ("d1"). innerHTML = response;
                }
            }
        }

Complex Json string manipulation method:
If the format of the JSON string we want to convert is:
{
    "encoding": "UTF-8",
    "plug-ins": ["python", "c ++", "ruby"],
    "indent": {
        "length": 3,
        "use_space": true
    }
}
Then write the corresponding serialized class, pay attention to the following attributes added by the Indent class:
[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;}
}

Output JSON string
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);
result:
JSON string is:
{"encoding": "UTF-8", "plugins": ["python", "C ++", "C #"], "indent": {"length": 4, "use_space": false}}

Read the contents of the Json string:
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);
result:
Encoding is: UTF-8
plugins is: python
plugins is: C ++
plugins is: C #
indent.length is: 4
indent.use_space is: False

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.