在很多涉及到网络通讯的地方,往往会用到JSON,初次接触这个东西,真的很令人头痛。不过有了Newtonsoft,这一切就变得出奇地简单:
1、创建一个JSON
String apiClass = "apiClass";
String apiCommand = "apiCommand";
String apiJsonParam = "apiJsonParam";
JObject postedJObject = new JObject();
postedJObject.Add("class", apiClass);
postedJObject.Add("cmd", apiCommand);
postedJObject.Add("param", apiJsonParam);
String paramString = postedJObject.ToString(Newtonsoft.Json.Formatting.None, null);
是不是很简单?
那么paramString 的结果是什么呢?
{"class":"apiClass","cmd":"apiCommand","param":"apiJsonParam"}
格式化一下
{
"class": "apiClass",
"cmd": "apiCommand",
"param": "apiJsonParam"
}
2、再创建一个嵌套的
String apiClass = "apiClass";
String apiCommand = "apiCommand";
JObject postedJObject = new JObject();
postedJObject.Add("class", apiClass);
postedJObject.Add("cmd", apiCommand);
String param1 = "param1";
String param2 = "param2";
JObject apiJsonParam = new JObject();
apiJsonParam.Add("param1", param1);
apiJsonParam.Add("param2", param2);
postedJObject.Add("param", apiJsonParam);
String paramString = postedJObject.ToString(Newtonsoft.Json.Formatting.None, null);
格式化的字符串呢?
{
"class": "apiClass",
"cmd": "apiCommand",
"param": {
"param1": "param1",
"param2": "param2"
}
}
3、再来一个添加了数组的
String apiClass = "apiClass";
String apiCommand = "apiCommand";
JObject postedJObject = new JObject();
postedJObject.Add("class", apiClass);
postedJObject.Add("cmd", apiCommand);
String param1 = "param1";
String param2 = "param2";
JObject apiJsonParam = new JObject();
apiJsonParam.Add("param1", param1);
apiJsonParam.Add("param2", param2);
postedJObject.Add("param", apiJsonParam);
JArray jArray = new JArray();
JObject arr1 = new JObject();
arr1.Add("arr1", "this is arr1");
jArray.Add(arr1);
JObject arr2 = new JObject();
arr2.Add("arr2", "this is arr2");
jArray.Add(arr2);
postedJObject.Add("jarray", jArray);
String paramString = postedJObject.ToString(Newtonsoft.Json.Formatting.Indented, null);
那么JSON字符串又是怎么样呢?
{
"class": "apiClass",
"cmd": "apiCommand",
"param": {
"param1": "param1",
"param2": "param2"
},
"jarray": [
{
"arr1": "this is arr1"
},
{
"arr2": "this is arr2"
}
]
}
是不是很简单?