我正在尝试以这种格式反序列化JSON:
{
"data": [
{
"installed": 1,
"user_likes": 1,
"user_education_history": 1,
"friends_education_history": 1,
"bookmarked": 1
}
]
}
到这样的简单字符串数组:
{
"installed",
"user_likes",
"user_education_history",
"friends_education_history",
"bookmarked"
}
使用JSON.NET 4.0
我已经使用`CustomCreationConverter'
开始工作了public class ListConverter : CustomCreationConverter<List<string>>
{
public override List<string> Create(Type objectType)
{
return new List<string>();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var lst = new List<string>();
//don't care about the inital 'data' element
reader.Read();
while (reader.Read())
{
if (reader.TokenType == JsonToken.PropertyName)
{
lst.Add(reader.Value.ToString());
}
}
return lst;
}
}
但这看起来有点矫枉过正,特别是如果我想为许多不同的json响应创建一个。
我尝试使用JObject
,但似乎我做得不对:
List<string> lst = new List<string>();
JObject j = JObject.Parse(json_string);
foreach (JProperty p in j.SelectToken("data").Children().Children())
{
lst.Add(p.Name);
}
有更好的方法吗?
答案 0 :(得分:6)
有很多方法可以做到这一点,你所拥有的就是好的。其他一些替代方案如下所示:
使用SelectToken
通过一次调用转到第一个数组元素
string json = @"{
""data"": [
{
""installed"": 1,
""user_likes"": 1,
""user_education_history"": 1,
""friends_education_history"": 1,
""bookmarked"": 1
}
]
}";
JObject j = JObject.Parse(json);
// Directly traversing the graph
var lst = j["data"][0].Select(jp => ((JProperty)jp).Name).ToList();
Console.WriteLine(string.Join("--", lst));
// Using SelectToken
lst = j.SelectToken("data[0]").Children<JProperty>().Select(p => p.Name).ToList();
Console.WriteLine(string.Join("--", lst));
答案 1 :(得分:0)
您也可以使用此解决方案来获取键和值:
string key, value;
var propertyList = (JObject)j["data"];
foreach (var property in propertyList)
{
key = property.Key;
value = property.Value.ToString();
}