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

时间:2011-08-04 01:57:22

标签: c# asp.net json datacontractjsonserializer

我有以下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 个答案:

答案 0 :(得分: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; }
}