如何使用 C# 在有效负载中使用事件关键字反序列化 JSON
How to Deserialise JSON with Event Keyword in Payload using C#
我在 Azure Function
收到来自 EventHub
的关注 JSON
Event {"Id":"cfbfbc8900b2","DateTime:"2021-04-29T08:01:26","NewId":null,"UserId":null}
我需要知道如何反序列化此负载,因为我遇到了以下错误。我已经尝试了一些来自 SO 的反序列化解决方案,但由于 JSON
开头的保留关键字 Event
,其中 none 似乎有效
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: E. Path '', line 0, position 0.'
这是 C# 代码
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);
}
}
}
}
你在 json 中有一个错误,“DateTime 应该是“DateTime”
{"Id":"cfbfbc8900b2","DateTime:"2021-04-29T08:01:26",...
你现在可以反序列化了
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; }
}
我在 Azure Function
EventHub
的关注 JSON
Event {"Id":"cfbfbc8900b2","DateTime:"2021-04-29T08:01:26","NewId":null,"UserId":null}
我需要知道如何反序列化此负载,因为我遇到了以下错误。我已经尝试了一些来自 SO 的反序列化解决方案,但由于 JSON
Event
,其中 none 似乎有效
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: E. Path '', line 0, position 0.'
这是 C# 代码
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);
}
}
}
}
你在 json 中有一个错误,“DateTime 应该是“DateTime”
{"Id":"cfbfbc8900b2","DateTime:"2021-04-29T08:01:26",...
你现在可以反序列化了
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; }
}