使用JSON.NET读取动态属性名称 [英] Using JSON.NET to read a dynamic property name
本文介绍了使用JSON.NET读取动态属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用来自外部API的数据,该数据返回JSON,如下所示.
I am using data from an external API that returns JSON such as the following.
{
"data": {
"4": {
"id": "12",
"email": "q23rfedsafsadf",
"first_name": "lachlan",
使用JSON.NET,如何获取4
值?这是动态的,因为它会针对每条记录(而不是我曾经使用过的最理想的API)进行更改.
Using JSON.NET, how do I get the 4
value? This is dynamic as it changes for each record (not the most ideal API I've ever used).
推荐答案
这是一个正常工作的dotNetFiddle: https://dotnetfiddle.net /6Zq5Ry
这是代码:
Here's a working dotNetFiddle: https://dotnetfiddle.net/6Zq5Ry
Here's the code:
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; }
}
这是输出:
这篇关于使用JSON.NET读取动态属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文