开发者

Deserializing JSON in ASP.NET C#

I have the following JSON:

{
  "recipe": {
    "rating": 19.1623, 
    "source_name": "Allrecipes", 
    "thumb": "http://img.punchfork.net/8f7e340c11de66216b5627966e355438_250x250.jpg", 
    "title": "Homemade Apple Crumble", 
    "source_url": "http://allrecipes.com/Recipe/Homemade-Apple-Crumble/Detail.aspx", 
    "pf_url": "http://punchfork.com/recipe/Homemade-Apple-Crumble-Allrecipes", 
    "published": "2005-09-22T13:00:00", 
    "shortcode": "z53PAv", 
    "source_img": "http://images.media-allrecipes.com/site/allrecipes/area/community/userphoto/big/173284.jpg"
  }
}

I'm trying to create a C# class that represents this data (I'm only interested in these three properties for the time being):

[Serializable]
[DataContract(Name = "recipe")]
public class Recipe
{
    [DataMember]
    public string thumb { get; set; }

    [DataMember]
    public string title { get; set; }

    [DataMember]
    public string source_url { get; set; }
}

I'm using the following code, which isn't working as expected. All the property values for Recipe are returning null. Any ideas where I'm going wrong here?

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Recipe));
Me开发者_运维技巧moryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));
Recipe recipe = serializer.ReadObject(ms) as Recipe;


The problem here is that the object you want is actually a sub-object off of the "recipes" parameter. Your class should be:

[DataContract]
public class Result
{
    [DataMember(Name = "recipe")]
    public Recipe Recipe { get; set; }
}

[DataContract]
public class Recipe
{
    [DataMember]
    public string thumb { get; set; }

    [DataMember]
    public string title { get; set; }

    [DataMember]
    public string source_url { get; set; }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜