繁体   English   中英

如何从 C# .net core 中的动态 json 对象读取数据

[英]how to read data from dynamic json object in C# .net core

我有 json 数据在 Web API 中动态传入,需要通读数据,但我无处可去,也不知道如何在 c# 类中将以下 json 数据声明为字符串或动态?

json数据

{
"sessionA": [
 {
   "order": 0,
   "type": "hidden",
   "name": "formId",
 },
{
  "order": 0,
  "type": "hidden",
  "name": "consultationId",
},
{
  "order": 0,
  "type": "hidden",
  "name": "clientId",
}
],
"sessionB": [
{
  "order": 0,
  "type": "heading",
  "label": "Super Quiz",
  "name": "title",
  "value": "Super Quiz",
  "validations": []
},
{
  "order": 5,
  "type": "separator",
  "label": "",
  "name": "separator",
  "value": "",
  "validations": []
  }
 ]
}

c#测试控制台类

class Program
{
    static void Main(string[] args)
    {

        dynamic myjson = "   {
"sessionA": [
 {
   "order": 0,
   "type": "hidden",
   "name": "formId",
 },
{
  "order": 0,
  "type": "hidden",
  "name": "consultationId",
},
{
  "order": 0,
  "type": "hidden",
  "name": "clientId",
}
],
"sessionB": [
{
  "order": 0,
  "type": "heading",
  "label": "Super Quiz",
  "name": "title",
  "value": "Super Quiz",
  "validations": []
},
{
  "order": 5,
  "type": "separator",
  "label": "",
  "name": "separator",
  "value": "",
  "validations": []
  }
 ]
}
";

        Console.WriteLine("dynamic json convert to object");
        Console.WriteLine("---------------------------------");



        Console.Read();
    }
}

您可以使用 Newtonsoft Json.net https://www.newtonsoft.com/json来解析 .NET 中的 JSON 数据,这可以通过 Nuget 获得。

var myjson = @"{
    ""sessionA"": [
     {
       ""order"": 0,
       ""type"": ""hidden"",
       ""name"": ""formId"",
     },
    {
      ""order"": 0,
      ""type"": ""hidden"",
      ""name"": ""consultationId"",
    },
    {
      ""order"": 0,
      ""type"": ""hidden"",
      ""name"": ""clientId"",
    }
    ],
    ""sessionB"": [
    {
      ""order"": 0,
      ""type"": ""heading"",
      ""label"": ""Super Quiz"",
      ""name"": ""title"",
      ""value"": ""Super Quiz"",
      ""validations"": []
    },
    {
      ""order"": 5,
      ""type"": ""separator"",
      ""label"": """",
      ""name"": ""separator"",
      ""value"": """",
      ""validations"": []
      }
     ]
    }";

dynamic myObject = JToken.Parse(myjson);
// Log sessionA first order
Console.WriteLine(myObject.sessionA[0].order);

// Another option
JToken jToken = JToken.Parse(myjson);

// Get Session B first label
var label = jToken.SelectToken("sessionB[0].label").Value<string>();
Console.WriteLine("Label: " + label);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM