无法在c#中将Json String转换为Json对象

时间:2017-11-21 07:47:07

标签: 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;
            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.

请告诉我如何做到这一点。

2 个答案:

答案 0 :(得分:1)

您的字符串无效JSON:

receiveCount(`{\"url\":\"http://www.google.com\",\"count\":75108}`)

有效的JSON部分是参数:

{"url":"http://www.google.com","count":75108}

您必须从字符串中提取有效的JSON部分以对其进行反序列化。

答案 1 :(得分:0)

你正在调用错误的财产。

你应该使用

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);