如何检查JArray是空的

时间:2015-05-07 06:50:26

标签: c# arrays dotnet-httpclient is-empty

我通过HttpClient调用API并获得如下响应。

{
  "result_set": []
}

我将响应解析为动态对象。

dynamic dbResponseBody = await dbResponse.Content.ReadAsAsync<object>();

如何检查result_set是否为空。目前我正在做如下但寻找更好的方法。

if (dbResponseBody.Result.result_set != "[]") {}

1 个答案:

答案 0 :(得分:1)

如果您知道类型,可以为响应构建模型。

class Response
{
        [JsonProperty("result_set")]
        public List<string> ResultSet { get; set; }
}

如果您的阵列模型中的项目更复杂,您可以构建以下

class Response
{
        [JsonProperty("result_set")]
        public List<Items> ResultSet { get; set; }
}

class Items{
     [JsonProperty("P1")]
     public string P1 { get; set; }
     [JsonProperty("P2")]
     public int P2 { get; set; }
}

然后您可以按如下方式阅读您的回复:

using (HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse)
                    {
                        if (response != null && response.StatusCode != HttpStatusCode.OK)
                            throw new Exception(String.Format(
                                "Server error (HTTP {0}: {1}).",
                                response.StatusCode,
                                response.StatusDescription));

                        if (response != null)
                        {
                            Stream responseStream = response.GetResponseStream();

                            Respose myResponse = GetResponseModel<Response>(responseStream);

                         }
                         else throw new Exception("My message");

使用Newtonsoft,您可以重新获得模型

protected T GetResponseModel<T>(Stream respStream) where T : class
        {
            if (respStream != null)
            {
                var respStreamReader = new StreamReader(respStream);
                Task<string> rspObj = respStreamReader.ReadToEndAsync();
                rspObj.Wait();

                Debug.WriteLine("Response: {0}", rspObj.Result);

                T jsonResponse = JsonConvert.DeserializeObject<T>(rspObj.Result);

                return jsonResponse;
            }

            return default(T);
        }

在此行结束后,您可以检查模型的属性

Respose myResponse = GetResponseModel<Response>(responseStream);

if(myResponse.Result.Count == 0){.....}