c# - Class with property that can be one of two different types -
i'm developing telegram bot in c# have difficulty implementing message
type. according api documentation, chat
field can either of type user
or of type groupchat
. how implement in c#?
so far come following code using newtonsoft.json
:
public class update { .... [jsonproperty("chat")] public user chat { get; set; } [jsonproperty("chat")] public groupchat group_chat { get; set; } .... }
but doesn't work webapi 2 controller method since deserialize message
using frombody
attribute:
public async task<httpresponsemessage> post(string token, [frombody] update update)
(type update
has field message
of type message
)
is there better way implement message
type?
since supposed handle seemingly 2 different objects in 1 field don't think can use strongly-typed objects can use dynamic type chat field such as
public class telegram { public int message_id { get; set; } public dynamic chat { get; set; } }
then can access variables , check if null or not understand if it's user or group chat:
static void main(string[] args) { string json = @"{ ""chat"": { ""id"": 1, ""first_name"": ""my_first_name"", ""last_name"": ""my_last_name"", ""username"": ""my_username"" }, ""message_id"": 123 }"; var telegram = newtonsoft.json.jsonconvert.deserializeobject<telegram>(json); string name = telegram.chat.first_name; // name = my_first_name string title = telegram.chat.title; // title = null }
Comments
Post a Comment