[英]How to use Json queries with c# using HttpClient
我正在使用C#連接到IBM Cloudant。 IBM Cloudant支持JSON查詢IBM Cloudant ,提到我需要使用POST請求才能創建查詢,但是沒有解釋,我使用的是HttpClient,它具有方法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#對象,您可以使用類似Newtonsoft.Json的內容對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>();
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>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.