c# - Can I control what subtype to use when deserializing a JSON string? -


i'm working facebook api , it's search method returns json response this:

{    "data": [       {          "id": "1",          "message": "heck of babysitter...",          "name": "baby eating watermelon",          "type": "video"       },       {          "id": "2",          "message": "great produce deals",          "type": "status"       }    ] } 

i have class structure similar 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 use correct subclass based on type attribute?

if use the

system.web.script.serialization.javascriptserializer 

you can use overload in constructor add own class resolver:

javascriptserializer myserializer = new javascriptserializer(new facebookresolver()); 

an example how implement can found here on so: javascriptserializer custom type

but should replace the

"type": "video" 

part to

"__type": "video" 

since convention class.

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

Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -