我试图从使用JSON.Net的web服务抓取一些JSON数据。我得到的错误是一个意外的字符,同时解析json数据。我使用的代码如下:
HttpWebRequest request;
WebResponse response;
private void btnGet_Click(object sender, RoutedEventArgs e)
{
request = WebRequest.Create(@"http://http://domain.com/test/question.php") as HttpWebRequest;
request.BeginGetResponse(AfterRequest, null);
}
private void AfterRequest(IAsyncResult result)
{
response = request.EndGetResponse(result);
using (StreamReader sd = new StreamReader(response.GetResponseStream()))
{
string resultString = sd.ReadToEnd();
Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(resultString);
response.Close();
MessageBox.Show(values["Question"]);
}
}
我试图反序列化的数据是:
{"Question":"How old am i?","A":"20","B":"23","C":"25","D":"26","Z":"D"}
该数据通过php/mysql输出。知道是我的代码还是JSON数据无效吗?
谢谢编辑:我已经更新了我试图反序列化的数据,现在看起来像这样;{
"Question": "How old am i?",
"Answers": {
"A": "24",
"B": "25",
"C": "26",
"D": "27"
},
"Answer": "B"
}
您的JSON是"有效的",但它的形式很差,以获得您正在寻找的结果。我会将JSON的格式更改为:
{
"Question":"How old am i?",
"Answers":[
"A":"20",
"B":"23",
"C":"25",
"D":"26",
"Z":"D"]
}
通过将可能的答案移动到数组中,您可以更容易地将它们与问题分开,并且还可以扩展数据集以包含诸如"CorrectAnswer":"B"等项