Several ways of serializing and deserializing JSON in. Net

Time:2019-12-2

I. what is JSON

JSON (JavaScript object notation) is a lightweight data exchange format. It is based on a subset of ECMAScript (JS specification developed by European Computer Association) and uses a text format completely independent of programming language to store and represent data. The simple and clear hierarchy makes JSON an ideal data exchange language. It is easy for people to read and write, but also easy for machines to parse and generate, and effectively improve the efficiency of network transmission.

It is a format used by JavaScript to process data. Most of it is used to process the data exchange between JavaScript and web server. It transfers the data from the background web server to the foreground, and then uses JavaScript for processing, such as Ajax. It is a lightweight data exchange format independent of language and platform.

2. JSON syntax

1. JSON syntax rules

In JS, everything is an object. Therefore, any supported type can be represented by JSON, such as string, number, object, array, etc. But objects and arrays are two special and common types:

  1. Object is represented as a key value pair
  2. Data separated by commas
  3. Curly braces saving objects
  4. Square bracket save array

Object: the object is wrapped with curly braces in JS. The data structure is the key value pair structure of {key1: value1, key2: Value2,…}. In the object-oriented language, key is the attribute of the object and value is the corresponding value. Key names can be represented by integers and strings. The value can be of any type.


{"firstName": "Brett", "lastName": "McLaughlin"}

Array: array is the content wrapped by brackets [] in JS. The data structure is the index structure of [“. Net”, “JavaScript”, “Python”,…]. In JS, array is a kind of special data type. It can also use key value pairs like objects, but it still uses indexes a lot. Again, the value can be of any type.


{
  "people": [{
      "firstName": "zhang",
      "lastName": "san"
    },
    {
      "firstName": "li",
      "lastName": "si"
    }
  ]
}

2. JSON key / value pair

JSON key value pair is a way to save JS objects, which is similar to JS objects. The key names in key / value pair combination are written in front and wrapped in double quotation marks, separated by colon: followed by value: { " firstName " : " Json " } , which is easy to understand, equivalent to this JavaScript statement:  {firstName : " Json " } 

3. The relationship between JSON and JS objects

The relationship between JS objects can be understood as follows: JSON is the string representation of JS objects. It uses text to represent the information of a JS object, which is essentially a string. Such as:

Var obj = {A: 'hello', B: 'world'}; // this is an object. Note that key names can also be enclosed in quotation marks
Var JSON = '{"a": "hello", "B": "world"}'; // this is a JSON string, essentially a string

4. JSON and JS objects transfer to each other

To implement conversion from an object to a JSON string, use the JSON. Stringify () method:

Var JSON = JSON. Stringify ({A: 'hello', B: 'world'}); // the result is' {"a": "hello", "B": "world"} '

To implement the conversion from JSON to objects, use the JSON. Parse () method:

Var obj = JSON. Parse ('{"a": "hello", "B": "world"}'); // the result is {A: 'hello', B: 'world'}

III. JSON serialization method

1、JavaScriptSerializer

The namespace that needs to be introduced to use the JavaScript serializer method is in the assembly system.web.extensions.dll.


using System.Web.Script.Serialization;

PS: use [scriptignore] to mark properties that are not serialized

Code:

public ActionResult GetJsonDemo()
{
  // object
  DataModel model = new DataModel();
  model.ID = 1;
  model.Name = "ZhangSan";
  Model.sex = "female";
  model.Age = 18;

  // object序列化Json
  string strJson= JsonHelper.ObjectToJson(model);

  //JSON deserializing objects
  model= JsonHelper.JsonToObject<DataModel>(strJson);

  String strContent = "object serialization:" + strjson + "\ n"+
            "Deserialization value:" + model. Name + "" + model. Sex + "" + model. Age;
  return Content(strContent);
}

JsonHelper:

public class JsonHelper
{
  #Region first JavaScript serializer 
  //The namespace that needs to be introduced to use the JavaScript serializer method is in the assembly system.web.extensions.dll 
  //using System.Web.Script.Serialization;
  //Note: properties that are not serialized can be marked with [scriptignore]
  /// <summary>
  ///Serialization
  /// </summary>
  /// <param name="obj"></param>
  /// <returns></returns>
  public static string ObjectToJson(object obj)
  {
    JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
    return jsonSerialize.Serialize(obj);
  }

  /// <summary>
  ///Deserialization
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="strJson"></param>
  /// <returns></returns>
  public static T JsonToObject<T>(string strJson)
  {
    JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
    //Jsonserialize. Deserialize < dynamic > (strjson); // value model ["name"]; to use index value, object. Property cannot be used
    return jsonSerialize.Deserialize<T>(strJson);
  }
  #endregion
}

Result:

 

2、JSON.NET

The namespace using newtonsoft.json that needs to be introduced to use the json.net class library;

PS: use [jsonignore] to mark non serialized attributes

Code:

public ActionResult GetJsonDemo()
{
  // object
  DataModel model = new DataModel();
  model.ID = 2;
  model.Name = "LiSi";
  Model.sex = "male";
  model.Age = 20;

  // object序列化Json
  string strJson = JsonHelper.ObjectToJson(model);

  //JSON deserializing objects
  model = JsonHelper.JsonToObject<DataModel>(strJson);

  String strContent = "object serialization:" + strjson + "\ n"+
            "Deserialization value:" + model. Name + "" + model. Sex + "" + model. Age;
  return Content(strContent);
}

JsonHelper:

/// <summary>
///JSON help class
/// </summary>
public class JsonHelper
{
  #Region the second json.net 
  //The namespace using newtonsoft.json that needs to be introduced to use the json.net class library;
  //Note: attributes that are not serialized can be marked with [jsonignore]

  /// <summary>
  ///Serialization
  /// </summary>
  /// <param name="obj"></param>
  /// <returns></returns>
  public static string ObjectToJson(object obj)
  {
    return JsonConvert.SerializeObject(obj);
  }

  /// <summary>
  ///Deserialization
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <param name="strJson"></param>
  /// <returns></returns>
  public static T JsonToObject<T>(string strJson)
  {
    return JsonConvert.DeserializeObject<T>(strJson);
  }
  #endregion
}

Result:

 

3、DataContractJsonSerializer

The namespace that needs to be introduced to use the datacontractjsonserializer method is in system.runtime.serialization.dll.


using System.Runtime.Serialization.Json;

The contract [DataMember], [datacontract] in an entity must be added when serializing and deserializing using datacontractjsonserializer, but not for the other two methods.

PS: use [ignoredatamember] to mark properties that are not serialized

Code:

public ActionResult GetJsonDemo()
{
  // object
  DataModel model = new DataModel();
  model.ID = 3;
  model.Name = "Wangwu";
  Model.sex = "female";
  model.Age = 22;

  // object序列化Json
  string strJson = JsonHelper.ObjectToJson(model);

  //JSON deserializing objects
  model = JsonHelper.JsonToObject<DataModel>(strJson);

  String strContent = "object serialization:" + strjson + "\ n"+
            "Deserialization value:" + model. Name + "" + model. Sex + "" + model. Age;
  return Content(strContent);
}

JsonHelper:

/// <summary>
///JSON help class
/// </summary>
public class JsonHelper
{
 #Region third datacontractjsonserializer
 //The namespace that needs to be introduced to use the datacontractjsonserializer method, in system.runtime.serialization.dll
 //using System.Runtime.Serialization.Json;
 //Note: properties that are not serialized can be marked with [ignoredatamember]
 //The contract [DataMember], [datacontract] in the entity must be added for serialization and deserialization using datacontractjsonserializer
 //For the other two ways, it is not necessary to add, but also OK.
 
 /// <summary>
 ///Serialization
 /// </summary>
 /// <param name="obj"></param>
 /// <returns></returns>
 public static string ObjectToJson(object obj)
 {
   using (MemoryStream stream = new MemoryStream())
   {
     DataContractJsonSerializer jsonSerialize = new DataContractJsonSerializer(obj.GetType());
     jsonSerialize.WriteObject(stream, obj);
     return Encoding.UTF8.GetString(stream.ToArray());
   }
 }
 
 /// <summary>
 ///Deserialization
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="strJson"></param>
 /// <returns></returns>
 public static T JsonToObject<T>(string strJson)
 {
   using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(strJson)))
   {
     DataContractJsonSerializer jsonSerialize = new DataContractJsonSerializer(typeof(T));
     return (T)jsonSerialize.ReadObject(stream);
   }
 }
 
 #endregion
}

Result:

 

PS: DataModel


[DataContract]
public class DataModel
{
  [DataMember]
  public int ID { get; set; }

  [DataMember]
  public string Name { get; set; }

  [DataMember]
  public string Sex { get; set; }

  [DataMember]
  public int Age { get; set; }
}

Four, summary

1. There are three ways to serialize JSON

  1. JavaScript serializer class
  2. Json.net class library
  3. Datacontractjsonserializer class

2. Try to use json.net (open source) for serialization and deserialization with good performance.

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.