我正在寫東西Omegle的,而這是一種反應,我得到:使用Json.NET反序列化這種數據
{ "clientID" : "shard2:jgv1dnwhyffmld7kir5drlcwp7k6eu",
"events" : [ [ "waiting" ],
[ "statusInfo",
{ "antinudepercent" : 1.0,
"antinudeservers" : [ "waw1.omegle.com",
"waw2.omegle.com",
"waw3.omegle.com"
],
"count" : 28477,
"servers" : [ "front1.omegle.com",
"front8.omegle.com",
"front7.omegle.com",
"front9.omegle.com",
"front2.omegle.com",
"front5.omegle.com",
"front3.omegle.com",
"front6.omegle.com",
"front4.omegle.com"
],
"spyQueueTime" : 0.000099992752075199996,
"spyeeQueueTime" : 0.8086000442504,
"timestamp" : 1375197484.3550739
}
]
]
}
爲了把這個數據變成一本字典,我已經試過使用下面的函數:
private Dictionary<string, object> deserializeToDictionary(string jo)
{
Dictionary<string, object> values = JsonConvert.DeserializeObject<Dictionary<string, object>>(jo);
Dictionary<string, object> values2 = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> d in values)
{
if (d.Value.GetType().FullName.Contains("Newtonsoft.Json.Linq.JObject"))
{
values2.Add(d.Key, deserializeToDictionary(d.Value.ToString()));
}
else
{
values2.Add(d.Key, d.Value);
}
}
return values2;
}
不過,我得到以下錯誤:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary2[System.String,System.Object]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
我在做什麼錯?
這裏你的總體目標是什麼?您是否真的需要將信息嵌入到一系列嵌套字典中,或者您是否試圖將其轉化爲易於使用的類結構?你需要所有的信息還是隻是其中的一部分?這將有助於回答你的問題。 –
我並不需要所有的數據。我目前所做的只是使用IndexOf和Substring來過濾掉所有我不需要的東西,但是當數據與平時稍有不同時會導致錯誤。我一般只需要一些東西,比如'[[「typing」],[「gotMessage」,「Hello!」],[「stoppedTyping」],'' –