C# 无法在c中将Json字符串转换为Json对象#
我有一个Json字符串,它是C# 无法在c中将Json字符串转换为Json对象#,c#,json,console-application,C#,Json,Console Application,我有一个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;
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);
// 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);
编辑1:
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);
// 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);
我试着提取它,但仍然得到相同的错误你提取了什么?确切的错误是什么?如果提取JSON字符串,则不会出现错误,说明字符串以字符“r”开头。首先,我无法将其解析为JSON。。然后,只有我可以考虑从中获取数据。似乎url(例如:)在receiveCount方法中返回json字符串。因此,作为一种解决方法,我从回复中删除了不需要的文本。检查它是否工作。:)仅供参考,没有MIME类型“text/json”,“application/json”可能是合适的。(来源:)当我从文本中删除receivedcount,然后尝试将字符串解析为json时,它就起作用了