【问题标题】:How to check JArray is empty如何检查 JArray 是否为空
【发布时间】:2015-05-09 00:09:53
【问题描述】:

我正在通过 HttpClient 调用 API 并得到如下响应。

{
  "result_set": []
}

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

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

如何检查 result_set 是否为空。目前我正在执行以下操作,但正在寻找更好的方法。

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

【问题讨论】:

  • 想想你将如何迭代它。我对语法并不新鲜,但我认为动态 result_set 会有某种索引器和一个长度属性。您可以检查长度是否为 0。除此之外,您可能还需要检查 string.IsNullOrEmpty(result_set),以确保动态属性首先存在。
  • 谢谢@Yorye。有一个 count 属性,所以我使用了它。 if(dbResponseBody.Result.result_set.Count > 0)
  • 好像是json响应。你试过 JSON.NET 吗?您可以将响应解析为 json 对象,然后检查 result_set 是否等于 null 或空数组。

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


【解决方案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){.....}

【讨论】:

  • 不想构建模型怎么办?如果你只想检查 JArray 是否为空怎么办?
猜你喜欢
  • 2017-11-15
  • 2020-05-29
  • 2018-04-02
  • 2016-04-05
  • 2018-01-08
  • 2020-09-25
  • 2012-01-15
  • 2016-07-16
  • 2021-08-14
相关资源
最近更新 更多