5

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

{[]}
2
  • I don't think it's a valid json string. Commented Jun 28, 2016 at 8:19
  • I am sure it is not ;) @DannyChen Commented Jun 28, 2016 at 8:20

2 Answers 2

9

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)
{ }
Sign up to request clarification or add additional context in comments.

1 Comment

thanks! exactly what I needed, checking o.list.Count is the solution. I love stackoverflow... :)
1

The json is invalid (in the original question and in the accepted answer). You should include double quotes ...

{
    "list": []
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.