简体   繁体   中英

De-serialize JSON using JSON.net on WP7

I'm trying to grab some JSON data from a web service using JSON.Net. The error I'm getting is an unexpected character whilst parsing the json data. The code i'm using is as follows:

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

The data I'm trying to de-serialize is:

{"Question":"How old am i?","A":"20","B":"23","C":"25","D":"26","Z":"D"}

This data is outputted via php/mysql. Any idea's if it's my code or the JSON data that's invalid?

thanks EDIT: I've updated the data i'm trying to de-serialize, it now looks like this; { "Question": "How old am i?", "Answers": { "A": "24", "B": "25", "C": "26", "D": "27" }, "Answer": "B" }

Your JSON is "valid" but it is poorly formed to get the results you are looking for. I'd change the formatting of your JSON to such:

{
 "Question":"How old am i?",
 "Answers":[
   "A":"20",
   "B":"23",
   "C":"25",
   "D":"26",
   "Z":"D"]
}

By moving your possible answers into an array you make it easier to keep them separated from the question, and also make it so you can extend the data set to include items such as "CorrectAnswer":"B"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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