问题
I have a JSON response (which I have no control over) similar to this:
{"response":{
"a" : "value of a",
"b" : "value of b",
"c" : "value of c",
...
}}
Where:
- "a", "b", "c" are unknown names upfront.
- The number of items can vary.
All I need at the end is an array of strings for all the values. Keeping the names is a bonus (Dictionary?) but I need to browse values by the order in which they appear.
How would you achieve this using JSON.NET?
回答1:
You can use the JObject
class from the Newtonsoft.Json.Linq
namespace to deserialize the object into a DOM-like structure:
public class StackOverflow_10608188
{
public static void Test()
{
string json = @"{""response"":{
""a"" : ""value of a"",
""b"" : ""value of b"",
""c"" : ""value of c""
}}";
JObject jo = JObject.Parse(json);
foreach (JProperty property in jo["response"].Children())
{
Console.WriteLine(property.Value);
}
}
}
回答2:
This works but not very pretty. I believe you can exchange to json.net with JavaScriptSerializer
.
var json = "{\"response\":{\"a\":\"value of a\",\"b\":\"value of b\",\"c\":\"value of c\"}}";
var x = new System.Web.Script.Serialization.JavaScriptSerializer();
var res = x.Deserialize<IDictionary<string, IDictionary<string, string>>>(json);
foreach (var key in res.Keys)
{
foreach (var subkey in res[key].Keys)
{
Console.WriteLine(res[key][subkey]);
}
}
or
Console.WriteLine(res["response"]["a"]);
Console.WriteLine(res["response"]["b"]);
Console.WriteLine(res["response"]["c"]);
output:
value of a
value of b
value of c
来源:https://stackoverflow.com/questions/10608188/how-can-i-deserialize-a-json-object-that-uses-unspecified-and-variable-property