3

私は次の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"
  }
}

このデータを表すC#クラスを作成しようとしています(当面は、これら3つのプロパティにのみ関心があります)。

[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; }
}

次のコードを使用していますが、期待どおりに機能していません。のすべてのプロパティ値はRecipeを返してnullいます。私がここで間違っているアイデアはありますか?

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Recipe));
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));
Recipe recipe = serializer.ReadObject(ms) as Recipe;
4

1 に答える 1

4

ここでの問題は、必要なオブジェクトが実際には「レシピ」パラメーターから外れたサブオブジェクトであるということです。クラスは次のようになります。

[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; }
}
于 2011-08-04T02:51:16.780 に答える