[英]How to convert Json into C# object?
我有一个特定的 Json 想要转换为 C# class ZA8CFDE6331BD59EB2AC66F8911C4B:
Json:
{
"Database": "DEMO",
"Schema": "PUBLIC",
"Warehouse": "TEST_WH",
"Query": "Call proc();",
"Role": "SYSADMIN",
"IsOpsTestRequest": "false",
"QueryParameters": {
"Param1": "abc",
"Param2": "def"
}
}
Class:
public class Request_Body
{
public string Database { get; set; }
public string Schema { get; set; }
public string Warehouse { get; set; }
public string Query { get; set; }
public string Role { get; set; }
public string IsOpsTestRequest { get; set; }
public List<(string, string)> QueryParameters { get; set; }
}
I am sending this json while making a post request to my azure functions http function (durable functions) and then I am trying to convert this json to C# object.
如果我从 class 中删除QueryParameter
List 变量,并从 json 中删除QueryParameter
,则它运行完美,但我希望param2
中的这个QueryParameter
并且它应该是通用的,或者有时可能包含更多属性,如param1
和 param1。 所以应该是通用的。
In my http trigger function I am converting json to class object as follow:
Request_Body data = await req.Content.ReadAsAsync<Request_Body>();
如何反序列化 json?
QueryParameters
的 JSON 不代表列表或数组。 JSON 中的列表或数组将在值周围有方括号 ( [...]
)。
但是,JSON 可以由Dictionary<string, string>
表示。 所以你的 class 应该是这样的:
public class Request_Body
{
public string Database { get; set; }
public string Schema { get; set; }
public string Warehouse { get; set; }
public string Query { get; set; }
public string Role { get; set; }
public string IsOpsTestRequest { get; set; }
public Dictionary<string, string> QueryParameters { get; set; }
}
从 nuget 尝试 newtonsoft json package 并使用序列化和反序列化方法。 例如:
public class Account {
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; } }
Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine(account.Email);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.