c# NewtonJson Jarray check null/empty error

John O. picture John O. · May 20, 2016 · Viewed 9.7k times · Source

How we can check a json array is null or emty?

Json:

    {
          "productList": [
            {
              "id": 2440,
              "serviceStatus": 1,
              "listOfBillProductsExtras": [
                {
                  "id": 2441,
                  "amount": 1,
                  "balance": 2,
                }
                                         ],
               "deskName": "Desk 1",
               "onlyTime": "15:25"
            },
            {
              "id": 2441,
              "serviceStatus": 1,
              "listOfBillProductsExtras": [ ],
               "deskName": "Desk2",
               "onlyTime": "15:27"
            }
     ]
  }

I try

JArray productList = JArray.Parse(content["productList"].ToString());

but it didn't work. (There was exp. Null Referance ) So, I want to check listOfBillProductsExtras array is null or empty. If not empty I will get the id, amount, balance.

Answer

David picture David · May 20, 2016

Parse the Json object to jArray:

  public ActionResult Method(object[] data)
  {
        var productList = Json.ParseJsonObjectToJArray(data, "productList");

        if(jArray.Count > 0)
        {

        }
    }

    public class Json
    {
        public static JArray ParseJsonObjectToJArray(object[] data, string objectName)
        {
             dynamic jObject = JObject.Parse(data[0].ToString());
             var info = jObject[objectName];

             return info;
        }
   }