在ASP.NET C#中反序列化JSON

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#类来表示这些数据(目前我只对这三个属性感兴趣):

[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;
1个回答

4

这里的问题是你想要的对象实际上是“recipes”参数的子对象。你的类应该是:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接