Bilal Shafqat
Bilal Shafqat

Reputation: 821

How to convert Json into C# object?

I have a specific Json that I want to convert to C# class object:

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.

If I remove QueryParameter List variable from class and also remove QueryParameter from json than it runs perfect but I want this QueryParameter in json and it should be generic - it can contain further attributes like param1 and param2 or sometimes maybe more. So it should be generic.

In my http trigger function I am converting json to class object as follow:

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

How can I deserialize the json?

Upvotes: 0

Views: 230

Answers (2)

Shub
Shub

Reputation: 13

Try newtonsoft json package from nuget and use serialize and deserialize methods. For example:

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

Upvotes: 0

haldo
haldo

Reputation: 16701

The JSON for QueryParameters does not represent a list or array. A list or array in JSON would have square brackets ([...]) surrounding the values.

However, the JSON can be represented by Dictionary<string, string>. So your class should look like this:

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

Upvotes: 4

Related Questions