mammago
mammago

Reputation: 247

Deserialize a JSON object with varying types in child objects

How can I deserialize an Object when types of it's child objects vary? I get the following JSON from Telegram Bot API:

{  
   "ok":true,
   "result":[  
   {  
     "update_id":126107325,
     "message":{  
        "message_id":200,
        "from":{  
           "id":someid,
           "first_name":"somename"
        },
        "chat":{  
           "id":someid,
           "title":"asdasdasdasd"
        },
        "date":1438327336,
        "text":"\/lfdngdf"
     }
  }
 ]
}

Where "chat" represents an object of the type "GroupChat".

When calling the same method again it could result in this:

{  
   "ok":true,
   "result":[  
  {  
     "update_id":126107326,
     "message":{  
        "message_id":204,
        "from":{  
           "id":1234567,
           "first_name":"somename"
        },
        "chat":{  
           "id":1234567,
           "first_name":"Paul"
        },
        "date":1438327788,
        "text":"\/blaaa"
     }
  }
]
}

Where chat represents an object oh type "User". I browsed some answers but they didnt help as im not directly Deserializing "Message" but "UpdatePacket" instead.

Thanks in advance!

Upvotes: 2

Views: 993

Answers (1)

yannick
yannick

Reputation: 121

    public class TelegramBoApiMainObject
    {
        public Boolean ok { get; set; }
        public List<TelegramBotApiResult> result { get; set; }
    }

    public class TelegramBotApiResult
    {
        public Int32 update_id { get; set; }
        public TelegramBotApiMessage message { get; set; }
    }

    public class TelegramBotApiMessage
    {
        public Int32 message_id { get; set; }
        public TelegramBotApiFrom from { get; set; }
        public TelegramBotApiChat chat { get; set; }
        public Int32 date { get; set; }
        public String text { get; set; }
    }

    public class TelegramBotApiFrom
    {
        public Int32 id { get; set; }
        public String first_name { get; set; }
    }

    public class TelegramBotApiChat
    {
        public Int32 id { get; set; }
        public String first_name { get; set; }
        public String title { get; set; }
    }

And then you can do something like to have GroupChat or User

var json = "...."; // one of your json string
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<TelegramBoApiMainObject>(json);
    var chat = obj.result[0].message.chat;
    if (String.IsNullOrEmpty(chat.title))
    {
        // user
    }
    else 
    {
        // group chat
    }

Upvotes: 3

Related Questions