[英]Unable to convert Json String to Json Object in c#
我有一個Json字符串,它是receiveCount({\\"url\\":\\"http://www.google.com\\",\\"count\\":75108})
我完整的方法是
public void GetPinCount(string url)
{
string QUrl = "https://api.pinterest.com/v1/urls/count.json?callback=receiveCount&url=" + url;
System.Net.HttpWebRequest Request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(QUrl);
Request.ContentType = "text/json";
Request.Timeout = 10000;
Request.Method = "GET";
string content;
using (WebResponse myResponse = Request.GetResponse())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8))
{
content = sr.ReadToEnd();
}
};
var json = JObject.Parse(content);
var share_count = json["receiveCount"]["count"].ToString();
Console.WriteLine("Share Count :" + share_count);
}
當我嘗試訪問計數時,出現了類似的異常
Unexpected character encountered while parsing value: r. Path '', line 0, position 0.
請告訴我該怎么做。
您的字符串不是有效的JSON:
receiveCount(`{\"url\":\"http://www.google.com\",\"count\":75108}`)
有效的JSON部分是參數:
{"url":"http://www.google.com","count":75108}
您必須從字符串中提取有效的JSON部分以反序列化。
您正在調用錯誤的屬性。
你應該用
var share_count = json["count"].ToString();
代替,
var share_count = json["receiveCount"]["count"].ToString();
用於響應的代碼:
var json = JObject.Parse (content);
var share_url = json["url"];
Console.WriteLine ("Share URL:" + share_url);
var share_count = json["count"];
Console.WriteLine ("Share Count:" + share_count);
編輯1:
// Gets only the JSON string we need
content = content.Replace ("receiveCount(", "");
content = content.Remove (content.Length - 1);
// Converts JSON string to Object
var json = JObject.Parse (content);
var share_url = json["url"];
Console.WriteLine ("Share URL:" + share_url);
var share_count = json["count"];
Console.WriteLine ("Share Count:" + share_count);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.