I am facing the following scenario. A project of mine is throwing an event that contains the following object:
public class MyEvent : BaseEvent
{
public long Id { get; set; }
public Dictionary<string, long> Pairs { get; set; }
}
I received the event and read the data as byte[] on my receiver side. The current code I have to read any generic event is:
public static T Decode(byte[] data)
{
var serializer = JsonSerializer.Create(new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
using (var stream = new MemoryStream(data))
{
using (var sr = new StreamReader(stream, Encoding.UTF8))
{
var jr = new JsonTextReader(sr);
var aux = Encoding.UTF8.GetString(data);
return serializer.Deserialize(jr, typeof(T)) as T;
}
}
}
where T is my class MyEvent . Unfortunately the thrown exception is:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.Int64]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. Path 'OperationTimePairs', line 1, position 61.
The way I read it is that the object received doesn't have the correct format.. however if I try to read it through var aux = Encoding.UTF8.GetString(data); I can see that the structure is the correct one. Any idea how can I fix this? Thanks!
EDIT:
Json Example:
{
"Timestamp":"\/Date(1540996292134)\/",
"Pairs":[
{
"Key":"first time",
"Value":28
},
{
"Key":"second time",
"Value":30
},
{
"Key":"third time",
"Value":101
},
{
"Key":"operation time",
"Value":231
}
],
"Id":123637
}