user3663854 user3663854 - 5 months ago 78
JSON Question

C# json object with empty json array

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

{[]}

Answer

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)
{ }