0

I have a JSON object like the following

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

I want to parse it using 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. How should I be mapping these?

3
  • You need to define a "from" class to match the json data. Same thing for "to" (if it differs from "from" in structure) and "data" Commented Aug 17, 2012 at 20:14
  • If you don't like having a lot of classes around you can use structs as well. I prefer them because they are just data like the JSON. Commented Aug 17, 2012 at 20:29
  • How about dynamic obj = JsonConvert.DeserializeObject(json); var name = obj.data[0].from.name; ? Commented Aug 18, 2012 at 20:56

2 Answers 2

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

Try below code :)

Sign up to request clarification or add additional context in comments.

Comments

0

Use this site to get the object for .net

Then you can use JSON.Net to deserialize: ex.JsonConvert.DeserializeObject(input) iirc

1 Comment

can't I do this directly? I was more interested in an attribute-based approach using JSON.NET features

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.