In C #, how to convert List & lt; custom & gt; To Json format and related functions-DataContractJsonSerializer,

Source: Internet
Author: User
Tags tojson

In C #, how do I convert List <custom> to Json format and related functions-DataContractJsonSerializer,

Summarize the conversion methods of C # And. net using List <custom> and Json format


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 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 <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 = ""; // serialize 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 the custom data structure:

For example:

Public class TestListResult <T>: List <T>
{
Public TestListResult ()
{
This. Successed = false;
This. Message = "";
}
Public bool Successed {get; set ;}
Public string Message {get; set ;}
}

Used in the same way as in a file.

After understanding the above principles, you can use the following functions in the project:

List <T> to 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 to 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 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 to multiple models in the form of 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 ();}

Convert a single object to 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);    }}

Encapsulate a function into a class,Easier to reference in projects:

Public class JsonHelper {// <summary> // generate Json format /// </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> /// obtain the 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> /// reverse return the JSON data to the foreground // </summary> /// <param name = "dt"> data table </param> /// <returns> JSON string </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 type for table conversion:
Public static class JsonTableHelper {// <summary> // returns Object serialization /// </summary> /// <param name = "obj"> source object </param >/// <returns> json data </returns> public static string ToJson (this object obj) {JavaScriptSerializer serialize = new JavaScriptSerializer (); return serialize. serialize (obj );} /// <summary> /// Control depth /// </summary> /// <param name = "obj"> source object </param> /// <param name = "recursionDepth"> depth </param> // <returns> json data </returns> public static string ToJson (this object obj, int recursionDepth) {JavaScriptSerializer serialize = new JavaScriptSerializer (); serialize. recursionLimit = recursionDepth; return serialize. serialize (obj );} /// <summary> /// convert the DataTable to json /// </summary> /// <param name = "dt"> DataTable </param> /// <returns> json data </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 );}}

Transmission of Json data in front and back ends in Asp.net

I. the foreground generates Json data and transmits it to the background for processing.

Javascript and Json. js are used to generate json data on the foreground.

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


Front-end 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:

Like the preceding conversion principle, we first create a json data class to facilitate use in List <>.

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

Functions for converting the Json data submitted at the front end

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

Call the above functions in the background code to process the data people:

// Obtain the 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 ();

Final result:

List <TestObj> Users = new List <TestObj> (); Users. add (new TestObj ("t1", "1", "male"); Users. add (new TestObj ("t2", "2", "female"); string json = Json. toJsJson (Users); Response. write (json); Response. end ();

2. Obtain the Json data submitted by the background at the front end

The following describes how to generate Json data in the background:

 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 Data Structure /// </summary> [DataContract] class ResultJson {[DataMember] public bool Result; [DataMember] public int Count; [DataMember] public string Message ;}

The foreground retrieves 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; // directly output // document. getElementById ("d1 "). innerHTML = response ;}}}

Complex Json string operations:

Assume that the JSON string format to be converted 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 attributes added by the Indent class below:
[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 Json string content:

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-8plugins is: pythonplugins is: C++plugins is: C#indent.length is: 4indent.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.