首页 > 解决方案 > 如何在动态反序列化 .NET 后访问 JSON 属性

问题描述

我正在创建 C# 控制台应用程序,我在其中使用 API 并获取 JSON 响应。反序列化后如何访问该 JSON 中的 JSON 属性

var json = JsonConvert.DeserializeObject<dynamic>(originalJson);

在 JS 中json.valuejson["value"]将工作,但在这里....没有

我正在尝试使用我变得非常非常复杂的动态 cuz 响应。所以上课并反序列化到那个班级,不。

{
    "@odata.context": "fff",
    "value": [
        {
            "@odata.etag": "\"3eee8ca6-7382-4760-88ec-8b759592123a,1\"",
            "createdDateTime": "2021-01-04T16:25:34Z",
            "eTag": "\"3eee8ca6-7382-4760-88ec-8b759592123a,1\"",
            "id": "1",
            "lastModifiedDateTime": "2021-01-04T16:25:34Z",
            "webUrl": "fff",
            "createdBy": {
                "user": {
                    "email": "ff",
                    "id": "2a95b5a3-c3a2-4fed-9490-d5e370fa643c",
                    "displayName": "ffff"
                }
            },
            "lastModifiedBy": {
                "user": {
                    "email": "ff",
                    "id": "2a95b5a3-c3a2-4fed-9490-d5e370fa643c",
                    "displayName": "ff"
                }
            },
            "parentReference": {
                "siteId": "dddd"
            },
            "contentType": {
                "id": "ddd",
                "name": "Item"
            },
            "fields@odata.context": "a",
            "fields": {
                "@odata.etag": "\"gg\"",
                "id": "1",
                "ContentType": "Item",
                "Title": "What is your name?",
                "Modified": "2021-01-04T16:25:34Z",
                "Created": "2021-01-04T16:25:34Z",
                "AuthorLookupId": "9",
                "EditorLookupId": "9",
                "_UIVersionString": "1.0",
                "Attachments": false,
                "Edit": "",
                "LinkTitleNoMenu": "What is your name?",
                "LinkTitle": "What is your name?",
                "ItemChildCount": "0",
                "FolderChildCount": "0",
                "_ComplianceFlags": "",
                "_ComplianceTag": "",
                "_ComplianceTagWrittenTime": "",
                "_ComplianceTagUserId": "",
                "Answer": "g"
            }
        }
    ]
}




using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.Azure.CognitiveServices.Knowledge.QnAMaker;
using Microsoft.Azure.CognitiveServices.Knowledge.QnAMaker.Models;
using Newtonsoft.Json.Linq;

标签: c#json.net.net-core

解决方案


您需要使用反射:

foreach (var property in json.GetType().Properties)
{
    var propertyName = property.Name;
    var propertyValue = property.GetValue();
}

推荐阅读