Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize list of object json by NewtonSoft?

I Serialize below class by Newtonsoft.Json but i can't Deserialize the same json by Newtonsoft.Json. How can i do that?

Json:

"{\"UserEvents\":[{\"id\":1214308,\"Date\":20150801000000,\"IsRead\":true}]}"

My Entities:

   public class UserEventLog {
    [JsonProperty("UserEvents")]
    public List<UserEvent> UserEvents { get; set; }
    public UserEventLog() {
        UserEvents = new List<UserEvent>();
    }
}


public class UserEvent {
    [JsonProperty("id")]
    public long id{ get; set; }
      [JsonProperty("Date")]
    public long Date{ get; set; }
      [JsonProperty("IsRead")]
    public bool IsRead { get; set; }
}

My Deserializer is that :

  List<UserEventLog> convert = JsonConvert.DeserializeObject<List<UserEventLog>>(user.ToString()) as List<UserEventLog>;

But Error is produced:

An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll

Additional information: Error converting value "{"UserEvents":[{"id":1214308,"Date":20150801000000,"IsRead":true}]}" to type 'System.Collections.Generic.List`1

How can i solve it? how can i Deserialize my List of object to UserEvents list?

like image 701
ALEXALEXIYEV Avatar asked Feb 09 '23 22:02

ALEXALEXIYEV


1 Answers

This works in linqpad:

void Main()
{
    var user = "{\"UserEvents\":[{\"id\":1214308,\"Date\":20150801000000,\"IsRead\":true}]}";
    UserEventLog convert = JsonConvert.DeserializeObject<UserEventLog>(user.ToString());
    convert.UserEvents.Count().Dump();
}

public class UserEventLog 
{
    [JsonProperty("UserEvents")]
    public List<UserEvent> UserEvents { get; set; }

    public UserEventLog() 
    {
        UserEvents = new List<UserEvent>();
    }
}


public class UserEvent 
{
    [JsonProperty("id")]
    public long id { get; set; }

    [JsonProperty("Date")]
    public long Date { get; set; }

    [JsonProperty("IsRead")]
    public bool IsRead { get; set; }
}

The problem is that you're trying to deserialize into list, but it is not an array of UserEvents

like image 79
Igoris Azanovas Avatar answered Feb 12 '23 11:02

Igoris Azanovas