4

I'm working with Facebook API and it's search method returns a JSON response like this:

{
   "data": [
      {
         "id": "1",
         "message": "Heck of a babysitter...",
         "name": "Baby eating a watermelon",
         "type": "video"
      },
      {
         "id": "2",
         "message": "Great Produce Deals",
         "type": "status"
      }
   ]
}

I have a class structure similar to this:

[DataContract]
public class Item
{
    [DataMember(Name = "id")]
    public string Id { get; set; }
}

[DataContract]
public class Status : Item
{
    [DataMember(Name = "message")]
    public string Message { get; set; }
}

[DataContract]
public class Video : Item
{
    [DataMember(Name = "string")]
    public string Name { get; set; }

    [DataMember(Name = "message")]
    public string Message { get; set; }
}

[DataContract]
public class SearchResults
{
    [DataMember(Name = "data")]
    public List<Item> Results { get; set; }
}

How can I use correct subclass based on that type attribute?

1
  • 1
    Found this question helpful, so I +1 it to counter lame down vote. Commented Aug 29, 2011 at 4:00

1 Answer 1

4

If you use the

System.Web.Script.Serialization.JavaScriptSerializer

you can use the overload in the constructor to add your own class resolver:

JavaScriptSerializer myserializer = new JavaScriptSerializer(new FacebookResolver());

An example how to implement this can be found here on SO: JavaScriptSerializer with custom Type

But you should replace the

"type": "video"

part to

"__type": "video"

since this is the convention for the class.

Here is an example:

public class FacebookResolver : SimpleTypeResolver
{
    public FacebookResolver() { }
    public override Type ResolveType(string id)
    {
        if(id == "video") return typeof(Video);
        else if (id == "status") return typeof(Status)
        else return base.ResolveType(id);
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Interesting! I've made some changes and that FacebookResolver is firing. But I can't see my public List<Item> Results { get; set; } filled; Am I missing something?
Just found another hint: when I use JavaScriptSerializer.DeserializeObject, I can see all children objects serialized, but inside a data property. Seems something is missing mapping DataMember(Name="data") attribute to that List<Item> Results property
Seems that __type property MUST be first one in JSON string; I tried to build a regex to order that attributes, but it's very hard to do. Bottom line: I gave up trying to specialize that JSON objects and used a denormalized version.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.