C# 在 ASP.NET MVC 中解析 JSON 值时出错?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10869119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error parsing JSON values in ASP.NET MVC?
提问by Man8Blue
I am trying to use StackOverflow's search API to search questions.
我正在尝试使用 StackOverflow 的搜索 API 来搜索问题。
I am using this action to perform the parsing :
我正在使用此操作来执行解析:
public ActionResult StackExchange(string sq)
{
string url = "http://api.stackoverflow.com/1.1/search?intitle=" + sq + "&order=desc";
var client = new WebClient();
var response = client.DownloadString(new Uri(url));
JObject o = JObject.Parse(response);// ERROR
int total = (int)o["total"];
return View(total);
}
Here is the JSON url I am trying to parse:
这是我试图解析的 JSON 网址:
http://api.stackoverflow.com/1.1/search?intitle=asp.net%20custom%20404&order=desc
http://api.stackoverflow.com/1.1/search?intitle=asp.net%20custom%20404&order=desc
I am trying to extract the following data:
我正在尝试提取以下数据:
`"total": 3` ,
`"question_timeline_url": "/questions/10868557/timeline",`
`"title": "Asp.net custom 404 not working using Intelligencia rewriter"`
Its giving error as : Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: . Path '', line 0, position 0.
它给出的错误为:Newtonsoft.Json.JsonReaderException:解析值时遇到意外字符:。路径 '',第 0 行,位置 0。
What can be the reason for the exception? I used the same method earlier and it worked fine.
异常的原因是什么?我之前用过同样的方法,效果很好。
Please suggest.
请建议。
采纳答案by Christophe Geers
Try the following approach.
尝试以下方法。
Use NuGet and reference the JSON.NET package. I see you've already done this.
使用 NuGet 并引用 JSON.NET 包。我看你已经这样做了。
Compose a request and get the response.
编写请求并获得响应。
string url = "http://api.stackoverflow.com/1.1/search?intitle=test&order=desc";
var request = (HttpWebRequest) WebRequest.Create(url);
var response = request.GetResponse();
The response you receive from the Stack Exchange API is gzipped! You first need to unzip it before you can read the JSON response. This is why you are receiving exceptions.
您从 Stack Exchange API 收到的响应已被压缩!您首先需要解压缩它,然后才能读取 JSON 响应。这就是您收到异常的原因。
Let's create a method which does just that. .NET provides us with the handy GZipStream type for this purpose.
让我们创建一个方法来做到这一点。为此,.NET 为我们提供了方便的 GZipStream 类型。
private string ExtractJsonResponse(WebResponse response)
{
string json;
using (var outStream = new MemoryStream())
using (var zipStream = new GZipStream(response.GetResponseStream(),
CompressionMode.Decompress))
{
zipStream.CopyTo(outStream);
outStream.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(outStream, Encoding.UTF8))
{
json = reader.ReadToEnd();
}
}
return json;
}
Now you can extract the JSON data from the response.
现在您可以从响应中提取 JSON 数据。
var json = ExtractJsonResponse(response);
Now you can parse the returned data.
现在您可以解析返回的数据。
JObject o = JObject.Parse(json);
int total = (int)o["total"];
PS: I would recommend you use version 2.0 of the API which has been released earlier this year.
PS:我建议您使用今年早些时候发布的 API 2.0 版。
回答by saintedlama
My first guess since JsonReader gives an exception at line 0, position 0 is that something is messed up with the encoding. Since the request above shows the following Content-Typeheader in chrome developer tools
自从 JsonReader 在第 0 行给出异常后,我的第一个猜测是位置 0 是编码有问题。由于上面的请求在 chrome 开发者工具中显示了以下Content-Type标头
Content-Type:application/json; charset=utf-8
You can try to set the encoding WebClient uses to utf-8 via WebClient's Encoding property.
您可以尝试通过 WebClient 的Encoding 属性将 WebClient 使用的编码设置为 utf-8 。

