如何使用 HttpClient 在 C# 中使用 Json 查询

How to use Json queries with c# using HttpClient

我正在使用 C# 连接到 IBM Cloudant。 IBM Cloudant 支持 JSON 查询 IBM Cloudant, it is mentioned that I need to use a POST request in order to create a query but it is not explained, I am using HttpClient which has a method PostAsync 方法。 有谁知道如何使用此方法创建查询,例如以下查询:

{
   "selector": {
      "_id": {
         "$gt": null
      }
   }
}

我对此也有些困惑。请参考以下内容。

var client = new HttpClient();

var content = new StringContent("JSON Content");
content.Headers.Add("header-name", "header value");

client.PostAsync("http://example.com/something", content);

您的 JSON 内容也可以是 C# 对象,您可以 JSON 使用 Newtonsoft.Json

之类的东西对其进行序列化

您也可以尝试这个版本,类 用于您的查询

public class Id{
    public object gt { get; set; }
}

public class Selector{
    public Id _id { get; set; }
}

public class RootObject{
    public Selector selector { get; set; }
}

序列化 tmpObject 和 PostAsync:


client.PostAsync(url, new StringContent(tmpObject.ToString(), Encoding.UTF8, "application/json"));

所以我终于设法检索了查询的响应,如下所示: var jsonString = "{\"selector\": {\"_id\": {\"$gt\": null}},\"fields\": [\"" + Attribute + "\"],\"sort\": [{\"_id\": \"asc\"}]}"; var content = new StringContent(jsonString, Encoding.UTF8, "application/json"); HttpResponseMessage res = await Client.PostAsync(string.Format("https://{0}.cloudant.com/{1}/_find", User, Database), content); StreamReader streamReader = new StreamReader(await res.Content.ReadAsStreamAsync()); JObject responseContent = (JObject)JToken.ReadFrom(new JsonTextReader(streamReader)); streamReader.Close(); var Elements =responseContent["docs"].Value<JArray>();