C#對(duì)Json進(jìn)行序列化和反序列化
一、Json簡介
Json(JavaScript Object Notation) 是一種輕量級(jí)的數(shù)據(jù)交換格式。它基于JS的一個(gè)子集。 Json采用完全獨(dú)立于語言的文本格式。這使得Json成為理想的數(shù)據(jù)交換語言。易于人閱讀和編寫,同時(shí)也易于機(jī)器解析和生成。
Json簡單來說就是JS中的對(duì)象和數(shù)組,所以Json也存在兩種結(jié)構(gòu):對(duì)象、數(shù)組。
Json對(duì)象:Json對(duì)象定義在花括號(hào)“{}”內(nèi),以Key:value鍵值對(duì)的形式存放數(shù)據(jù),多個(gè)數(shù)據(jù)使用分號(hào)“;”分割。
二、序列化
Object obj = Serialization.JsonToObject<Object>(strJson);
三、反序列化
strJson = Serialization.ObjectToJSON(obj);
四、工具類
public static class Serialization
{
public static T JsonToObject<T>(string jsonText)
{
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(T));
MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonText));
T result = (T)((object)dataContractJsonSerializer.ReadObject(memoryStream));
memoryStream.Dispose();
return result;
}
public static string ObjectToJSON<T>(T obj)
{
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(T));
string result = string.Empty;
using (MemoryStream memoryStream = new MemoryStream())
{
dataContractJsonSerializer.WriteObject(memoryStream, obj);
memoryStream.Position = 0L;
using (StreamReader streamReader = new StreamReader(memoryStream))
{
result = streamReader.ReadToEnd();
}
}
return result;
}
}JSONStrToList
自定義模型
public class Obj
{
public string Name { get; set; }
public double Price { get; set; }
}JSONStrToList
//json轉(zhuǎn)對(duì)象、數(shù)組, 反序列化
public static void JSONStringToList()
{
//json格式字符串
string JsonStr = "{Name:'蘋果',Price:5.5}";
JavaScriptSerializer Serializer = new JavaScriptSerializer();
//json字符串轉(zhuǎn)為對(duì)象, 反序列化
Obj obj = Serializer.Deserialize<Obj>(JsonStr);
Console.Write(obj.Name + ":" + obj.Price + "\r\n");
//json格式字符串
string JsonStrs = "[{Name:'蘋果',Price:5.5},{Name:'橘子',Price:2.5},{Name:'柿子',Price:16}]";
JavaScriptSerializer Serializers = new JavaScriptSerializer();
//json字符串轉(zhuǎn)為數(shù)組對(duì)象, 反序列化
List<Obj> objs = Serializers.Deserialize<List<Obj>>(JsonStrs);
foreach (var item in objs)
{
Console.Write(item.Name + ":" + item.Price + "\r\n");
}
}StrTosJSON
public static JObject strToJson(string jsonText)
{
jsonText = "{\"shenzheng\":\"深圳\",\"beijing\":\"北京\",\"shanghai\":[{\"zj1\":\"zj11\",\"zj2\":\"zj22\"},\"zjs\"]}";
JObject jo = (JObject)JsonConvert.DeserializeObject(jsonText);
//或者
//JObject jo = JObject.Parse(jsonText);
string zone = jo["shenzheng"].ToString();//輸出 "深圳"
string zone_en = jo["shanghai"].ToString();//輸出 "[{"zj1":"zj11","zj2":"zj22"},"zjs"]"
string zj1 = jo["shanghai"][1].ToString();//輸出 "zjs"
Console.WriteLine(jo);
return jo;
}到此這篇關(guān)于C#對(duì)Json進(jìn)行序列化和反序列化的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#中使用WinRAR實(shí)現(xiàn)加密壓縮及解壓縮文件
這篇文章主要介紹了C#中使用WinRAR實(shí)現(xiàn)加密壓縮及解壓縮文件,本文直接給出實(shí)例代碼,代碼中包含詳細(xì)注釋,需要的朋友可以參考下2015-07-07

