我在Web API中有动态传入的json数据,需要读取数据,但我无处可去,也不确定如何在c#类中声明以下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": []
}
]
}
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();
}
}
答案 0 :(得分:1)
您可以使用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);