使用 Newtonsoft Json 获取 json 属性类型

ope*_*sas 1 json json.net .net-core

我用 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();
}
Run Code Online (Sandbox Code Playgroud)

我想一定有某种方法可以从属性中获取 json 类型。(这里现场小提琴)

Bri*_*ers 5

Valuea 的是JPropertya JToken。您可以使用Typea 的属性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();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)