4
我想以這種形式進行反序列化JSON:使用JObject和JProperty與JSON.Net 4.0
{
"data": [
{
"installed": 1,
"user_likes": 1,
"user_education_history": 1,
"friends_education_history": 1,
"bookmarked": 1
}
]
}
一個簡單的字符串數組是這樣的:使用JSON.NET 4.0
{
"installed",
"user_likes",
"user_education_history",
"friends_education_history",
"bookmarked"
}
我已經得到它來工作`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);
}
有沒有更好的方式來做到這一點?
有沒有在性能上還是那些東西2種方法之間有什麼區別? – Clox
如果有的話,我想可能會忽略不計。但是,一如既往,嘗試在你的情景中,衡量它,併爲自己做出決定。 – carlosfigueira