Json Object to a Multidimensional C# Array?
Is there a way t开发者_运维问答o convert a Json Object to a Multidimensional C# Array? I know it might be impractical but I can't be bothered to write classes and then deserialize the strings into them.
List<string> ohyeah = (List<string>)JsonConvert.DeserializeObject(g.CommToken);
That returns an Invalid Cast exception!
Example:
{"method":"getCommunicationToken","header":{"uuid":"9B39AAB0-49A6-AC7A-BA74-DE9DA66C62B7","clientRevision":"20100323.02","session":"c0d3e8b5d661f74c68ad72af17aeb5a1","client":"gslite"},"parameters":{"secretKey":"d9b687fa10c927f102cde9c085f9377f"}}
I need to get something like that :
j["method"]; //This will equal to getCommunicationToken
j["header"]["uuid"]; //This will equal to 9B39AAB0-49A6-AC7A-BA74-DE9DA66C62B7
I literally need to parse the json object into an array.
The Parse and SelectToken methods of the JObject class do exactly what you want/need. The Library can be found here: 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'
By the way: This is not a multidimensional array:
j["header"]["uuid"];
You would have those indexers for example in a dictionary with dictionaries as values, like:
Dictionary<string, Dictionary<string, string>> j;
But here you would just have a "depth" of two indexes. If you want a datastructure with indexers in this "jagged array style", you would write a class like:
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'...
}
}
}
精彩评论