一个API向我返回了以下的json:
{
"query":{
"pages":{
"49123":{
"pageid":49123,
"ns":0,
"title":"Phoenix (constellation)",
"revisions":[
{
"revid":588710862,
"parentid":588710834
}
]
}
}
}
}
我用 json2csharp 构建了一个表示这个 json 的类(我手动调整了 PageInfo 的名称,因为它无法识别这个名称并将其称为 __invalid_type__49123)。
public class Revision
{
public int revid { get; set; }
public int parentid { get; set; }
}
public class PageInfo
{
public int pageid { get; set; }
public int ns { get; set; }
public string title { get; set; }
public List<Revision> revisions { get; set; }
}
public class Pages
{
public PageInfo pageInfo { get; set; }
}
public class Query
{
public Pages pages { get; set; }
}
public class RootObject
{
public Query query { get; set; }
}
并尝试对其进行解析:
var json = "{\"query\":{\"pages\":{\"49123\":{\"pageid\":49123,\"ns\":0,\"title\":\"Phoenix (constellation)\",\"revisions\":[{\"revid\":588710862,\"parentid\":588710834}]}}}}";
// unescaped version of json below
// {"query":{"pages":{"49123":{"pageid":49123,"ns":0,"title":"Phoenix (constellation)","revisions":[{"revid":588710862,"parentid":588710834}]}}}}
var root = JsonConvert.DeserializeObject<RootObject>(json);
我可以检查和查看root.query.pages都有值,但pageInfo为null。我不确定缺少什么使我能够将此JSON加载到对象中。
49123
没有映射到Pages
类中的PageInfo
属性。这是一个有趣的情况,因为它看起来特定元素在JSON
中是PageId
的值,所以对于您的JSON
字符串的每个实例都会不同。如果它是一个常量,您可以在Pages
类中的PageInfo
属性上使用[JsonProperty(PropertyName = "Myname")]
装饰。 - Shiva