Can I control which subtype to use when deserializing a JSON string?

I am working with the Facebook API, and the search method returns a JSON response as follows:

{
   "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 like 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 the correct subclass based on this attribute type?

+3
source share
1 answer

If you use

System.Web.Script.Serialization.JavaScriptSerializer

you can use overloading in the constructor to add your own class recognizer:

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

An example of how to implement this can be found here on SO: JavaScript with a custom type

But you have to replace

"type": "video"

"__type": "video"

.

:

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);
    }
}
+3

Source: https://habr.com/ru/post/1756429/


All Articles