Json格式與對象之間的映射關係
大括號與中括號
- 大括號({}):可以看作是一個對象,或者對應於程序中的對象,對象中可以包含屬性
大括號{}內部是採用key:value的形式,key可以是string,int等,value可以是string,int,或者是對象。具體的與對象的映射關係請參考第二節。
- 中括號([]):表示一個數組,要求其中的元素具有相同的結構和類型,e.g.,可以是string, int, 也可以是對象(i.e., 對應大括號)
與對象的映射
大括號映射爲對象
{
"cat": {
"name": "aa"
}
}
class Cat
{
public string name {get;set;}
}
class Demo
{
Cat cat {get;set;}
}
大括號映射爲字典
{
"cat": {
"name1": "aa",
"name2": "bb",
"name3": "cc"
}
}
class Demo
{
public Dictionary<string, string> cat {get;set;}
}
對象序列化與反序列化
序列化
using System.Web.Script.Serialization;
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
string str = serializer.Serialize(demo);
httpResp = new HttpResponseMessage { Content = new StringContent(str, System.Text.Encoding.GetEncoding("UTF-8"), "application/json") };
反序列化
using System.Web.Script.Serialization;
JavaScriptSerializer serializer = new JavaScriptSerializer();
inputParam = serializer.Deserialize<Demo>(strJsonText);