3

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));
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));
Recipe recipe = serializer.ReadObject(ms) as Recipe;

1 Answer 1

4

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; }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.