c# - 使用 JSON.Net 反序列化 $ref 文档指针

标签 c# .net json asp.net-web-api json.net

我已经熬了几个小时试图解决这个问题。似乎有很多帖子都在解决我遇到的问题,但似乎没有一个帖子对我有用。

我只是想使用 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");

编辑:

我回答了下面的问题。我不敢相信我必须这样做,但它确实有效。

最佳答案

哇...这就是我为解决问题所做的事情。我不确定是否有更简单的方法,而且我不敢相信 json.net 没有提供开箱即用的功能。

var x = JObject.Parse(json);
            var xx = x.Descendants().ToList().Where(d => d.Path.ToLower().EndsWith("$ref"));
            foreach (var item in xx)
            {
                if (!item.HasValues)
                    continue;
                string str = item.First.ToString().TrimStart(new char[] { '#' }).TrimStart(new char[] { '/' });
                var split = str.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            JToken token = x;
            for (int i = 0;i<split.Length; i++)
            {
                token = token[split[i]];
            }

            item.Parent.Replace(token);
        }

        var doc = JsonConvert.DeserializeObject<RootDoc>(x.ToString(), new JsonSerializerSettings()
        {
            PreserveReferencesHandling = PreserveReferencesHandling.Objects,
            ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
            Error = delegate (object sender, Newtonsoft.Json.Serialization.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# - 使用 JSON.Net 反序列化 $ref 文档指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35479089/

相关文章:

c# - 在 Windows 10 通用应用程序上检查平台

c# - 使用 EPPlus 库将公式替换为 Excel 中的值

java - 当运行启用了 proguad 的版本变体时,Gson 映射到 pojo 会返回 null,即使添加了 @SerializedName

json - 使用 Postgres 在多列上调用 to_json

c# - Json反序列化和ADO持久化过程中的字符串截断

c# - ASP.Net C# 路由; HTTP处理器;和 HttpModule 不工作

c# - 有没有办法查看 JITter 为给定的 C#/CIL 生成的 native 代码?

c# - WCF 无法从 net.tcp 获取元数据

c# - 如何知道 TriggerContext 当前更新的表?

javascript - Mustache.js 应该能够处理/显示空字符串