Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# json object with empty json array

Tags:

json

c#

I have a returned json object that contains an empty json array

{[]}

EDIT:

How do I check this in an if statement?

        string arrayData = string.Empty;

        if (response.Contains("\"data\":"))
        {
            JToken root = JObject.Parse(response);
            JToken data = root["data"];
            if (data != null)
            {
                arrayData = data.ToString();
            }
        }
        else
        {
            arrayData = response;
        }

        var responseDatas = JsonConvert.DeserializeObject<dynamic>(arrayData);

Here, responseDatas is now

{[]}
like image 317
user3663854 Avatar asked Jun 28 '16 08:06

user3663854


1 Answers

First, that is invalid JSON. The array should have a name, like this:

{ list: [] }

Second, you can deserialize the JSON using JSON.NET and then test the result:

public class ClassWithList
{
    public List<object> list { get; set; }
}

var o = JsonConvert.DeserializeObject<ClassWithList>(json);

if (o.list != null && o.list.Count > 0)
{ }
like image 148
Patrick Hofman Avatar answered Sep 29 '22 17:09

Patrick Hofman