简体   繁体   English

无法在C#中将Json字符串转换为Json对象

[英]Unable to convert Json String to Json Object in c#

I have an Json string which is receiveCount({\\"url\\":\\"http://www.google.com\\",\\"count\\":75108}) 我有一个Json字符串,它是receiveCount({\\"url\\":\\"http://www.google.com\\",\\"count\\":75108})

My complete Method is 我完整的方法是

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

When I am trying to access the count i am getting an exception like 当我尝试访问计数时,出现了类似的异常

Unexpected character encountered while parsing value: r. Path '', line 0, position 0.

Please tell me how this can be done. 请告诉我该怎么做。

Your string is not valid JSON : 您的字符串不是有效的JSON:

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

The valid JSON part is the parameter : 有效的JSON部分是参数:

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

You must extract the valid JSON part from your string to deserialize it. 您必须从字符串中提取有效的JSON部分以反序列化。

You are calling the wrong property. 您正在调用错误的属性。

You should use 你应该用

var share_count = json["count"].ToString();

instead of, 代替,

var share_count = json["receiveCount"]["count"].ToString();

Code to use with response: 用于响应的代码:

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

EDIT 1: 编辑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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM