使用JSON.NET读取动态属性名称

时间:2016-12-29 22:00:51

标签: c# json json.net

我正在使用返回JSON的外部API中的数据,如下所示。

{
  "data": {
    "4": {
      "id": "12",
      "email": "q23rfedsafsadf",
      "first_name": "lachlan",

使用JSON.NET,我如何获得4值?这是动态的,因为它改变了每条记录(不是我曾经使用过的最理想的API)。

1 个答案:

答案 0 :(得分:14)

这是一个有效的dotNetFiddle:https://dotnetfiddle.net/6Zq5Ry

以下是代码:

using System;
using Newtonsoft.Json;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        string json = @"{
                      'data': {
                        '4': {
                          'id': '12',
                          'email': 'lachlan12@somedomain.com',
                          'first_name': 'lachlan'
                          },
                        '5': {
                          'id': '15',
                          'email': 'appuswamy15email@somedomain.com',
                          'first_name': 'appuswamy'
                          }
                       }
                    }";

        var data = JsonConvert.DeserializeObject<RootObject>(json);
        Console.WriteLine("# of items deserialized : {0}", data.DataItems.Count);
        foreach ( var item in data.DataItems)
        {
            Console.WriteLine("  Item Key {0}: ", item.Key);
            Console.WriteLine("    id: {0}", item.Value.id);
            Console.WriteLine("    email: {0}", item.Value.email);
            Console.WriteLine("    first_name: {0}", item.Value.first_name);
        }
    }
}

public class RootObject
{
    [JsonProperty(PropertyName = "data")]
    public Dictionary<string,DataItem> DataItems { get; set; }
}

public class DataItem
{
    public string id { get; set; }
    public string email { get; set; }
    public string first_name { get; set; }
}

这是输出:

enter image description here

相关问题