简体   繁体   English

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

[英]How to deserialize JSON to .NET object using JSON.NET?

I have a JSON object like the following 我有一个如下的JSON对象

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

I want to parse it using JSON.NET , 我想使用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; }
}

Everything comes through except for the FeedId and the UserId properties. 除了FeedIdUserId属性外,其他所有内容都可以通过。 How should I be mapping these? 我应该如何映射这些?

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);

Try below code :) 试试下面的代码:)

Use this site to get the object for .net 使用此站点获取.net的对象

Then you can use JSON.Net to deserialize: ex.JsonConvert.DeserializeObject(input) iirc 然后,您可以使用JSON.Net反序列化:ex.JsonConvert.DeserializeObject(input)iirc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM