The first thing you need to reference in your project: Newtonsoft.Json.dll
Add Namespaces in your code: using Newtonsoft.json;
Two important methods and examples of JSON serialization and deserialization:
Jsonconvert.serializeobject (object value) serialization, which has an overloaded method Jsonconvert.serializeobject (object value, params jsonconverter [] converters)
Jsonconvert.deserializeobject (string value, type type) is deserialized, and it has an overloaded method Jsonconvert.deserializeobject (string value, type Type, params jsonconverter[] converters)
First, we first build a person class code as follows:
public class person{private string name; public string Name {get {return Name;} set {name = value;} } private int age; public int Age {get {return-age;} set {age = value;} }}
1. Serialization
Using system;using system.collections.generic;using system.linq;using system.web;using System.Web.UI;using System.web.ui.webcontrols;using Newtonsoft.json; namespace jsonnet{public partial class Test:System.Web.UI.Page { protected void Page_Load (object sender, EventArgs e) {person person = new person (); Person. Name = "Goldeneasy"; Person. Age =; String Strserializejson = Jsonconvert.serializeobject (person); Response.Write (Strserializejson);}}}
Output: {"Name": "Goldeneasy", "Age": 25}
2. Deserialization
Using system;using system.collections.generic;using system.linq;using system.web;using System.Web.UI;using System.web.ui.webcontrols;using Newtonsoft.json; namespace jsonnet{public partial class Test:System.Web.UI.Page { protected void Page_Load (object sender, EventArgs e) {person person = new person (); Person. Name = "Goldeneasy"; Person. Age =; String Strserializejson = Jsonconvert.serializeobject (person); Person user = (person) jsonconvert.deserializeobject (Strserializejson, typeof (person)); Response.Write (user. Name);}}}
Output Result: Goldeneasy
You can also use a template to get a JSON file by name
private static T parsejson<t> (string filename) { try { var filePath = configs.getpath (filename) ; if (! File.exists (FilePath)) return default (T); var content = File.readalltext (filePath); return jsonconvert.deserializeobject<t> (content); } catch (Exception ex) { Logger.Log ("File Parse" + ex.) Message); return default (T); } }
Using Newtonsoft.json in Unity to generate and read JSON