利用Newtonsoft.Json序列化,反序列化,读取,写入

using Newtonsoft.Json;

using Newtonsoft.Json.Converters;

//把Json 字符串反序列化为对象
目标对象 = JavaScriptConvert.DeserializeObject(JSON字符串, typeof (目标对象));

//把目标对象序列化为Json字符串
string Json字符串 = JavaScriptConvert.SerializeObject(目标对象);
代码:

protected void Page_Load(object sender, EventArgs e) { Student student = new Student("kntao", 20); student.Alias[0] = "小孔"; student.Alias[1] = "孔某某"; // 序列化 string outPut = JavaScriptConvert.SerializeObject(student); Response.Write("序列化输出============================</br>"); Response.Write(outPut + "</br>"); // 反序列化 Student stu = (Student)JavaScriptConvert.DeserializeObject(outPut, typeof(Student)); Response.Write("反序列化输出============================</br>"); Response.Write("Name:" + stu.Name + " Alias:" + stu.Alias[0]+"," +stu.Alias[1] + " Age:" + stu.Age + "</br>" ); // 读取JSON string jsonText = "['JSON!',1,true,{property:'value'}]"; JsonReader reader = new JsonReader(new StringReader(jsonText)); Response.Write("JSON 读取============================</br>"); while (reader.Read()) { Response.Write(reader.TokenType + "----" + reader.ValueType + "----" + reader.Value); Response.Write("</br>"); } // JSON写入 StringWriter sw = new StringWriter(); JsonWriter writer = new JsonWriter(sw); writer.WriteStartArray(); writer.WriteValue("JSON!"); writer.WriteValue(1); writer.WriteValue(true); writer.WriteStartObject(); writer.WritePropertyName("property"); writer.WriteValue("value"); writer.WriteEndObject(); writer.WriteEndArray(); writer.Flush(); string json = sw.GetStringBuilder().ToString(); Response.Write("JSON 写入============================</br>"); Response.Write(json + "</br>"); } 运行结果: 利用Newtonsoft.Json序列化,反序列化,读取,写入_第1张图片

 

你可能感兴趣的:(json,String,object,output)