Sara
Sara

Reputation: 43

Unable to use JSON array for Azure Function

I have below JSON input for My azure function but unable to pass it in after deserialize object

{
  "name": [{
      "SiteName": "Site1",
      "SiteUrl": "https://site1.com/"
    },
    {
      "SiteName": "Site2",
      "SiteUrl": "https://site2.com/"
    },
  ]
}

after deserialize I am getting count as 2 but inside array value I am not getting for deserializing using below code

string requestBody = new StreamReader(req.Body).ReadToEnd();
dynamic data = JsonConvert.DeserializeObject(requestBody);
       
var Root = data["name"].ToObject<List<Constant>>();

and for Constant class declared like below

class Constant
{
     public Dictionary<string, string> name { get; set; }
} 

Upvotes: 3

Views: 913

Answers (2)

Karan
Karan

Reputation: 12619

Try to create class like below.

class JsonResponse
{
    public List<Constant> name { get; set; }
}

class Constant
{
    public string SiteName { get; set; }
    public string SiteUrl { get; set; }
}

And try to Deserialize response with JsonConvert.DeserializeObject<JsonResponse>(requestBody).

string requestBody = new StreamReader(req.Body).ReadToEnd();
JsonResponse data = JsonConvert.DeserializeObject<JsonResponse>(requestBody);
var Root = data.name;

Upvotes: 2

Yong Shun
Yong Shun

Reputation: 51125

Solution 1: Deserialize as object list

The model class should be:

public class Site
{
    public string SiteName { get; set; }
    public string SiteUrl { get; set; }
} 

And deserialize as below:

var Root = data["name"].ToObject<List<Site>>();

Sample program (Site class)


Solution 2: Deserialize as Dictionary

var Root = data["name"].ToObject<List<Dictionary<string, string>>>();

Sample program (Dictionary)

Upvotes: 1

Related Questions