Home > Software engineering >  How to Deserialise JSON with Event Keyword in Payload using C#
How to Deserialise JSON with Event Keyword in Payload using C#

Time:03-02

I am receiving following JSON from EventHub in Azure Function

Event {"Id":"cfbfbc8900b2","DateTime:"2021-04-29T08:01:26","NewId":null,"UserId":null}

I need to know how to deserialise this payload as I am getting following error. I have tried few solutions from SO for deserialisation but none of them seem to work due to reserve keyword Event at the start of JSON

Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: E. Path '', line 0, position 0.'

Here is C# code

 foreach (EventData eventDataItem in events)
            {
                try
                {
                    var eventPayload = Encoding.UTF8.GetString(eventDataItem.EventBody);
                    dynamic eventData;
                    using (StringReader reader = new StringReader(eventPayload))
                    {
                        string line;
                        while ((line = reader.ReadLine()) != null)
                        {
                            eventData = JsonConvert.DeserializeObject<dynamic>(line);
                        }
                    }
                }
            }

CodePudding user response:

you have a bug in json, "DateTime should be "DateTime"

{"Id":"cfbfbc8900b2","DateTime:"2021-04-29T08:01:26",...

you can deserialize now

Event data = JsonConvert.DeserializeObject<Event>(json);

    public class Event
    {
    public string Id { get; set; }
    public DateTime DateTime { get; set; }
    public string NewId { get; set; }
    public string UserId { get; set; }
   }

  • Related