【发布时间】:2016-02-18 10:38:09
【问题描述】:
我已经花了好几个小时试图解决这个问题。似乎有很多帖子提示我遇到的问题,但似乎没有一个帖子对我有用。
我只是想使用 json.net 反序列化我的 json 文档中的 $ref 字段
示例 JSON:
{
"items": [
{ "$ref": "#/parameters/RequestId" },
{
"name": "user",
"in": "body",
"description": "User metadata object",
"required": true
}
],
"parameters": {
"RequestId": {
"name": "X-requestId",
"in": "header",
"description": "this is a request id",
"required": false
}
}
}
示例类:
public class Item
{
public string Name {get;set;}
public string In {get;set;}
public string Description {get;set;}
public bool Required {get;set;}
}
public class RootDoc
{
public List<Item> Items {get;set;}
public Dictionary<string, Item> Parameters {get;set;}
}
我的期望:
var doc = JsonConvert.DeserializeObject<RootDoc>(json, new JsonSerializerSettings()
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
Error = delegate (object sender, ErrorEventArgs args)
{
// Handle all errors
args.ErrorContext.Handled = true;
}
});
Assert.IsNotNull(doc);
Assert.IsNotNull(doc.Items);
Assert.IsTrue(doc.Items.Count == 2);
Assert.IsTrue(doc.Items[0].Name == "X-requestId");
Assert.IsTrue(doc.Items[1].Name == "user");
编辑:
我回答了下面的问题。我不敢相信我必须这样做,但它确实有效。
【问题讨论】:
标签: c# .net json asp.net-web-api json.net