【问题标题】:get a json property type with Newtonsoft Json使用 Newtonsoft Json 获取 json 属性类型
【发布时间】:2018-04-26 22:54:01
【问题描述】:

我用 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 类型。 (现场小提琴here

【问题讨论】:

  • 你试过p.Value.Type吗?
  • 您说得对,请发表您的评论作为答案,以便我接受

标签: json json.net .net-core


【解决方案1】:

JPropertyValueJToken。您可以使用 JToken 上的 Type 属性来获取其 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();
    }
  }
}

【讨论】:

  • 分叉小提琴的额外荣誉 ;-)))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-17
相关资源
最近更新 更多