【问题标题】:How to convert Json into C# object?如何将 Json 转换为 C# 对象?
【发布时间】:2020-04-08 17:27:57
【问题描述】:

我有一个要转换为 C# 类对象的特定 Json:

json:

{
    "Database": "DEMO",
    "Schema": "PUBLIC",
    "Warehouse": "TEST_WH",
    "Query": "Call proc();",
    "Role": "SYSADMIN",
    "IsOpsTestRequest": "false",
    "QueryParameters": {
        "Param1": "abc",
        "Param2": "def"
    }
}

类:

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; }
}

我在向我的 azure 函数 http 函数(持久函数)发出发布请求时发送此 json,然后我尝试将此 json 转换为 C# 对象。

如果我从类中删除 QueryParameter List 变量并从 json 中删除 QueryParameter 则它运行完美但我希望在 json 中使用此 QueryParameter 并且它应该是通用的 - 它可以包含更多属性,如 param1param2 或者有时可能更多。所以它应该是通用的。

在我的 http 触发函数中,我将 json 转换为类对象,如下所示:

Request_Body data = await req.Content.ReadAsAsync<Request_Body>();

如何反序列化 json?

【问题讨论】:

    标签: c# json azure-functions data-conversion azure-durable-functions


    【解决方案1】:

    QueryParameters 的 JSON 不代表列表或数组。 JSON 中的列表或数组在值周围会有方括号 ([...])。

    但是,JSON 可以用Dictionary&lt;string, string&gt; 表示。所以你的类应该是这样的:

    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; }
    }
    

    【讨论】:

      【解决方案2】:

      尝试使用 nuget 的 newtonsoft json 包并使用序列化和反序列化方法。例如:

      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);
      

      You can check here for more about this package

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-24
        • 2018-02-27
        • 2016-04-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多