Using JSON.NET to read a dynamic property name
我正在使用来自返回 JSON 的外部 API 的数据,如下所示。
|
1
2 3 4 5 6 |
{
“data”: { “4”: { “id”:“12”, “email”:“q23rfedsafsadf”, “first_name”:“lachlan”, |
使用 JSON.NET,我如何获得 4 值?这是动态的,因为每条记录都会发生变化(不是我用过的最理想的 API)。
- 反序列化为您的 data 字段值的字典,如将嵌套的 JSON 反序列化为 C# 对象或从 json 对象以 ID 作为名称创建强类型的 c# 对象中所示。
这是一个有效的 dotNetFiddle:https://dotnetfiddle.net/6Zq5Ry
这是代码:
|
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
using System;
using Newtonsoft.Json; using System.Collections.Generic; public class Program var data = JsonConvert.DeserializeObject<RootObject>(json); public class RootObject public class DataItem |
这是输出:

来源:https://www.codenong.com/41387782/
