使用Newtonsoft Json获得json属性类型

openas

我使用JObject.Parse(json)解析了一个Json字符串,并且试图遍历属性。我发现访问json类型的唯一方法是通过其父节点,如下所示:

string json = @"{
    CPU: 'Intel',
    Drives: [ 'DVD read/writer', '500 gigabyte hard drive'
    ]
}";
JObject o = JObject.Parse(json);

foreach (var p in o.Properties()) 
{
    Console.WriteLine("name:" + p.Name + ", value: " + p.Value);
    Console.WriteLine("o[p.Name].Type: " + o[p.Name].Type);  // correctly returns js type
    Console.WriteLine("p.Type: " + p.Type);  // returns Property for every item
    Console.WriteLine("p.GetType(): " + p.GetType()); // returns Newtonsoft.Json.Linq.JProperty for every item
    Console.WriteLine();
}

我想必须有某种方法可以从属性中获取json类型。在这里玩小提琴

布赖恩·罗杰斯

ValueJPropertyJToken您可以在Type使用属性JToken以获取其JSON类型。因此,您只需要使用p.Value.Type即可获得所需的内容。

小提琴示例:https : //dotnetfiddle.net/CtuGGz

using System;
using Newtonsoft.Json.Linq;

public class Program
{
  public static void Main()
  {
    string json = @"
        {
          ""CPU"": ""Intel"",
          ""Integrated Graphics"": true,
          ""USB Ports"": 6,
          ""OS Version"": 7.1,
          ""Drives"": [
            ""DVD read/writer"",
            ""500 gigabyte hard drive""
          ]
        }";
    
    JObject o = JObject.Parse(json);
    
    foreach (var p in o.Properties()) 
    {
        Console.WriteLine("name: " + p.Name);
        Console.WriteLine("type: " + p.Value.Type);
        Console.WriteLine("value: " + p.Value);
        Console.WriteLine();
    }
  }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章