如何使用JSON.NET将JSON反序列化为.NET对象?

时间:2012-08-17 20:06:25

标签: c# json.net

我有一个JSON对象,如下所示

{
   "data": [
      {
         "id": "18128270850211_49239570772655",
         "from": {
            "name": "Someone Unimportant",
            "id": "57583427"
         }
         /* more stuff */
      }
   ]
}

我想使用JSON.NET

解析它
FacebookResponse<FacebookPost> response = JsonConvert.DeserializeObject<FacebookResponse<FacebookPost>>(json);

internal class FacebookResponse<T> where T : class
{
    public IList<T> Data { get; set; }
    public FacebookResponsePaging Paging { get; set; }
}

public class FacebookPost
{
    public string Id { get; set; }

    [JsonProperty("to.data.id")]
    public string FeedId { get; set; }

    [JsonProperty("from.id")]
    public string UserId { get; set; }

    [JsonProperty("created_time")]
    public DateTime CreatedTime { get; set; }

    [JsonProperty("updated_time")]
    public DateTime UpdatedTime { get; set; }

    public string Type { get; set; } // TODO: Type enum??

    public string Message { get; set; }
    public string Link { get; set; }
    public string Name { get; set; }
    public string Caption { get; set; }
    public string Description { get; set; }
}

FeedIdUserId属性外,其他所有内容都会出现。我应该如何映射这些?

2 个答案:

答案 0 :(得分:1)

public class From
{
    public string name { get; set; }
    public string id { get; set; }
}

public class Datum
{
    public string id { get; set; }
    public From from { get; set; }
}

public class FacebookPost
{
    public List<Datum> data { get; set; }
}

internal class FacebookResponse<T> where T : class
{
    public IList<T> Data { get; set; }
    public FacebookResponsePaging Paging { get; set; }
}

FacebookResponse<FacebookPost> response = JsonConvert.DeserializeObject<FacebookResponse<FacebookPost>>(json);

尝试以下代码:)

答案 1 :(得分:0)

使用此site获取.net

的对象

然后你可以使用JSON.Net反序列化:ex.JsonConvert.DeserializeObject(输入)iirc