我使用JavaScriptSerializer()中内置的.Net来序列化来自网页的JSON字符串。我听说Newtonsoft.Json.Net有一个更好的序列化程序,所以我想试试。
我加载了json字符串,这里有一个示例。
jsonString = "{"jName":"MB-CEF3-4","StartDate":"08/20/2013 00:00","EndDate":"08/29/2013 00:00","JType":"General","SetupParams":[
{"Name":"PTitle","Title":"01. Period Title","Type":"text","Value":"TestName"},
{"Name":"PStart","Title":"02. Period Start","Type":"datetime","Value":"08/20/2013"},
{"Name":"Target","Title":"03. Target","Type":"int","Value":"1"},
{"Name":"URL","Title":"04. Completion Report URL","Type":"url","Value":"http://www.example.com"},
{"Name":"FormTitle","Title":"05. Form Title","Type":"text","Value":"ct"},
{"Name":"nvTypes","Title":"{B6E71787-EB51-45CF-B408-552F79AF2E7B}","Type":"nvc","Value":"Use of nv tools"}, {"Name":"NVCoachingTypes","Title":"","Type":"nvc","Value":""}]}";
JavaScriptSerializer scs = new JavaScriptSerializer();
Dictionary<String, Object> aps = (Dictionary<String, Object>)scs.DeserializeObject(ActSetupConfigs);
然后,我将把这个Dictionary传递到另一个工作类中,在那里它被反序列化。。
我使用的是:var parameters=((object[])parameters["SetupParams"]);
并且它将加载对象的数组。
我试着用Json.Net 做同样的事情
Dictionary<String, Object> aps = JsonConvert.DeserializeObject<Dictionary<String, Object>>(ActSetupConfigs);
但当我尝试反序列化它时,我不会得到对象的数组,相反,数组的子集合只是一个字符串。。。。所以它抛出了一个异常。如何使用Json.net序列化所有子集合?
SetupParams数组的子集合不是字符串,而是JToken
,它是JSON.Net用来保存JSON结构的通用容器对象。幸运的是,从JToken中提取值很容易。请尝试使用此代码。
JToken aps = JToken.Parse(jsonString);
foreach (JToken param in aps["SetupParams"])
{
Console.WriteLine("Name: " + param["Name"].Value<string>());
Console.WriteLine("Title: " + param["Title"].Value<string>());
Console.WriteLine("Type: " + param["Type"].Value<string>());
Console.WriteLine("Value: " + param["Value"].Value<string>());
Console.WriteLine();
}
您可以使用类似json.net的解析上述json响应
dynamic initialresp=JValue.Parse(jsonString);
string jname=Convert.ToString(initialresp.jname);
...
...
dynamic setupparams=JArray.Parse(Convert.ToString(initialresp.SetupParams));
foreach(var item in setupparams)
{
string name=Convert.Tostring(item.Name);
string title=Convert.Tostring(item.Title);
...
...
}
希望这能有所帮助。