Common JSON operations in. NET

Source: Internet
Author: User
Tags object serialization

1. JSON serialization and deserialization

Newtonsoft. Json dll http://json.codeplex.com/

Using System; using System. collections. generic; using System. linq; using System. text; using Newtonsoft. json; namespace PlayJSON {class Program {static void Main (string [] args) {List <StuInfo> list = new List <StuInfo> () {new StuInfo {StuName = "Zhang San", StuSex = "male", StuAge = 11}, new StuInfo {StuName = "Li Si", StuSex = "male ", stuAge = 32}, new StuInfo {StuName = "", StuSex = "female", StuAge = 64 }}; string jsonStr = JavaScriptConvert. serializeObject (list); // converts an object to a json storage Console. writeLine ("JSON string" + jsonStr); Console. readLine (); List <StuInfo> newList = new List <StuInfo> (); newList = (List <StuInfo>) JavaScriptConvert. deserializeObject (jsonStr, typeof (List <StuInfo>); // deserialization // StuInfo s = new StuInfo () {StuName = "Aaron", StuSex = "male ", stuAge = 33}; // string sigleJSON = JavaScriptConvert. serializeObject (s); // StuInfo newS = (StuInfo) JavaScriptConvert. deserializeObject (sigleJSON); // Console. writeLine ("name:" + newS. stuName + "--- Gender:" + newS. stuSex + "-- Age:" + newS. stuAge + "\ n"); foreach (StuInfo item in newList) {Console. writeLine ("name:" + item. stuName + "--- Gender:" + item. stuSex + "-- Age:" + item. stuAge + "\ n");} Console. readLine () ;}} public class StuInfo {public string StuName {set; get;} public string StuSex {set; get ;} public int StuAge {set; get ;}}}
 

2. In the web

/// <Summary> /// Handler1 abstract description /// </summary> public class Handler1: IHttpHandler {public void ProcessRequest (HttpContext context) {context. response. contentType = "application/json"; List <StuInfo> list = new List <StuInfo> () {new StuInfo {StuName = "zhangsan", StuSex = "male ", stuAge = 11}, new StuInfo {StuName = "", StuSex = "male", StuAge = 32}, new StuInfo {StuName = "Wang Cuihua ", stuSex = "female", StuAge = 64 }}; string jsonStr = JavaScriptConvert. serializeObject (list); context. response. write (jsonStr); context. response. end () ;}public bool IsReusable {get {return false ;}} public class StuInfo {public string StuName {set; get ;}public string StuSex {set; get ;} public int StuAge {set; get ;}}

Call on the front-end page: jquery ajax request is used here

    JSON                                             

Json is often used, so it is often needed to be serialized and deserialized .,. NET Framewok 3.5 also provides JSON Object Serialization and deserialization classes. This is the DataContractJsonSerializer class under the System. Runtime. Serialization. Json namespace. This class can be used to serialize and deserialize JSON objects.

Now I provide a class of JSON Object serialization and deserialization class for your reference:

/// <Summary> /// JSON help class. Converts an object to a Json string or a Json string to an object. /// </Summary> public static class JsonHelper {// <summary> // convert the object to a Json string /// </summary> /// <typeparam name = "T"> source type </typeparam> // <param name = "obj"> source type instance </param> /// <returns> Json string </returns> public static string GetJsonFromObj <T> (T obj) {DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer (obj. getType (); using (MemoryStream MS = new MemoryStream () {jsonSerializ Er. writeObject (MS, obj); return Encoding. UTF8.GetString (ms. toArray ());}} /// <summary> /// convert the Json string to an object // </summary> /// <typeparam name = "T"> target type </typeparam>/ // <param name = "strJson"> Json string </param> // <returns> an instance of the target type </returns> public static T GetObjFromJson <T> (string strJson) {T obj = Activator. createInstance <T> (); using (MemoryStream MS = new MemoryStream (Encoding. UTF8.GetBytes (strJso N) {DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer (obj. getType (); return (T) jsonSerializer. readObject (MS );}} /// <summary> /// convert the DataTable to a JSON string // </summary> /// <param name = "dt"> data table </param> // /<returns> JSON string </returns> public static string GetJsonFromDataTable (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 ;}} /// <summary> /// convert the object to a Json string // </summary> /// <param name = "obj"> source object </param>/ // <returns> json data </returns> public static string ObjToJson (this object obj) {JavaScriptSerializer serialize = new JavaScriptSerializer (); return serialize. serialize (obj );} /// <summary> /// convert a Json string to an object // </summary> /// <param name = "strJson"> Json string </param>/ // <returns> target object </returns> public static T JsonToObj <T> (string strJson) {JavaScriptSerializer serialize = new JavaScriptSerializer (); return serialize. deserialize <T> (strJson);} // <summary> // convert the object to a Json string (Control depth) /// </summary> /// <param name = "obj"> source object </param> /// <param name = "recursionDepth"> depth </param> /// <returns> json data </returns> public static string ObjToJson (this object obj, int recursionDepth) {JavaScriptSerializer serialize = new JavaScriptSerializer (); serialize. recursionLimit = recursionDepth; return serialize. serialize (obj);} // <summary> // convert a Json string to an object (Control depth) /// </summary> /// <param name = "strJson"> Json string </param> /// <param name = "recursionDepth"> depth </param> /// <returns> target object </returns> public static T JsonToObj <T> (string strJson, int recursionDepth) {JavaScriptSerializer serialize = new JavaScriptSerializer (); serialize. recursionLimit = recursionDepth; return serialize. deserialize <T> (strJson );} /// <summary> /// convert the DataTable to a JSON string // </summary> /// <param name = "dt"> DataTable </param> // /<returns> json data </returns> public static string DataTableToJson (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 ObjToJson (dic );}}

  Use:

 

JSON can be serialized and deserialized in C #, which is very convenient. The Code is as follows:

First introduce the namespace: using System. Web. Script. Serialization;

Define another class as follows:

public class jsonClass    {        public string id;        public string name;        public string pId;        public string isParent;        public string open;        public string senable;        public string CHECKED;        public string chkDisabled;    }

Convert a JSON string to a jsonClass instance as follows:

JavaScriptSerializer serializer = new JavaScriptSerializer();                    List<jsonClass> jsonClassList = serializer.Deserialize<List<jsonClass>>(jsonString);

Convert List <jsonClass> to json

string resultString = serializer.Serialize(jsonClassList);



Related Article

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.