[英]How to deserialize a json file with multidimensional array to convert it to object in c#
[英]Json Object to a Multidimensional C# Array?
有没有一种方法可以将Json对象转换为多维C#数组? 我知道这可能不切实际,但是我不必费心编写类,然后将字符串反序列化为它们。
List<string> ohyeah = (List<string>)JsonConvert.DeserializeObject(g.CommToken);
返回无效的Cast异常!
例:
{"method":"getCommunicationToken","header":{"uuid":"9B39AAB0-49A6-AC7A-BA74-DE9DA66C62B7","clientRevision":"20100323.02","session":"c0d3e8b5d661f74c68ad72af17aeb5a1","client":"gslite"},"parameters":{"secretKey":"d9b687fa10c927f102cde9c085f9377f"}}
我需要得到这样的东西:
j["method"]; //This will equal to getCommunicationToken
j["header"]["uuid"]; //This will equal to 9B39AAB0-49A6-AC7A-BA74-DE9DA66C62B7
我确实需要将json对象解析为一个数组。
JObject类的Parse和SelectToken方法可以完全满足您的需求。 可在以下位置找到该库: http : //json.codeplex.com/releases/view/37810
JObject o = JObject.Parse(@"
{
""method"":""getCommunicationToken"",
""header"":
{
""uuid"":""9B39AAB0-49A6-AC7A-BA74DE9DA66C62B7"",
""clientRevision"":""20100323.02"",
""session"":""c0d3e8b5d661f74c68ad72af17aeb5a1"",
""client"":""gslite""
},
""parameters"":
{
""secretKey"":""d9b687fa10c927f102cde9c085f9377f""
}
}");
string method = (string)o.SelectToken("method");
// contains now 'getCommunicationToken'
string uuid = (string)o.SelectToken("header.uuid");
// contains now '9B39AAB0-49A6-AC7A-BA74DE9DA66C62B7'
顺便说一句:这不是多维数组:
j["header"]["uuid"];
例如,您将那些索引器放在以字典为值的字典中,例如:
Dictionary<string, Dictionary<string, string>> j;
但是在这里,您只有两个索引的“深度”。 如果要使用带有这种“锯齿状数组样式”的索引器的数据结构,则可以编写类似以下的类:
class JaggedDictionary{
private Dictionary<string, string> leafs =
new Dictionary<string, string>();
private Dictionary<string, JaggedDictionary> nodes =
new Dictionary<string, JaggedDictionary>();
public object this[string str]
{
get
{
return nodes.Contains(str) ? nodes[str] :
leafs.Contains(str) ? leafs[str] : null;
}
set
{
// if value is an instance of JaggedDictionary put it in 'nodes',
// if it is a string put it in 'leafs'...
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.