I'm trying to parse data from my website and then deserializing it inside C# but I haven't gotten it work. What is the simplest way and method to use when grabbing dat开发者_如何学运维a from a http source and deserializing it in C#?
Based on the following JSON:
{
name: "Brad Christie",
score: 10,
questions: [
{
question_id: 1,
question: "How do I deserialize javascript?",
answer: "JavaScriptSerializer",
points: 10
}
]
}
and assuming these classes:
public class Question
{
public Int32 question_id;
public String questions;
public String answer;
public Int32 points;
}
public class JSExample
{
public String name;
public Int32 score;
IEnumerable<Question> questions;
}
the below should work (though didn't test and going by memory of what I've done in the past). Basically, the JavaScriptSerializer should take a JSON string and parse it out in to your custom object, or result in a dictionary of the structure of the JSON (I personally prefer placing it an object so i can manipulate it as I chose, but you can use the dictionary/dynamic variable and debug to see the result). Anyways, the code would be as follows:
//String the_JSON_string = <data from webpage>;
JavaScriptSerializer serializer = new JavaScriptSerializer();
JSExample example = serializer.Deserialize<JSExample>(the_JSON_string);
There are a number of JSON serializers in .NET. Most notably the built in DataContractSerializer
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx
EDIT:
(Sorry wrong link, here's the one for JSON
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx
and http://msdn.microsoft.com/en-us/library/bb410770.aspx)
and JSON.NET
http://json.codeplex.com/
精彩评论