0

i am downloading a JSON from a webserver and want to convert it in a List. I am using the Newtonsoft JsonConverter for this. This JSON is an array of radom chat messages.

JSON:

{  
   "messages":[  
      {  
         "_id":4,
         "_content":"ff",
         "_userName":"UAQ0FTQP5",
         "_timeStamp":"2018-06-04T11:46:00.000Z",
         "_processed":1
      },
      {  
         "_id":5,
         "_content":"Stop it mom",
         "_userName":"UAQ0FTQP5",
         "_timeStamp":"2018-06-04T11:47:22.000Z",
         "_processed":1
      },
      {  
         "_id":6,
         "_content":"General Kenobi",
         "_userName":"UB0QGN3EG",
         "_timeStamp":"2018-06-04T11:49:45.000Z",
         "_processed":1
      },
      {  
         "_id":7,
         "_content":"Hello General Kenobi",
         "_userName":"UB0QGN3EG",
         "_timeStamp":"2018-06-04T11:49:57.000Z",
         "_processed":1
      },
      {  
         "_id":8,
         "_content":"Hello there",
         "_userName":"UB15RMYDB",
         "_timeStamp":"2018-06-04T11:49:59.000Z",
         "_processed":1
      }
   ]
}

My Class:

public class Message
{
    [JsonProperty("_id")]
    public int ID {get; set;}
    [JsonProperty("_content")]
    public string Content { get; set; }
    [JsonProperty("_userName")]
    public string UserName { get; set; }
    [JsonProperty("_timeStamp")]
    public DateTime TimeStamp { get; set; }
    [JsonProperty("_processed")]
    public int Processed { get; set; }
}

This is my try to deserialize it: (variable JSON is a string which holds the JSON above)

List<Message> messages = JsonConvert.DeserializeObject<List<Message>>(JSON);

As I try this I get this error:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[mom.client.Logik.Message]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'messages', line 1, position 12.

Is there anybody who can show me where i am trapped? Any answer would be greatly appreciated.

Kind Regards.

Nisarg
  • 1,631
  • 6
  • 19
  • 31
  • 6
    Your JSON represents an object that contains a list. It doesn't directly represent a list. So you will need to create a wrapper object, (perhaps call it MessageCollection) and have that contain the `List` and then deserialize to that type. – mason Jun 05 '18 at 13:58
  • wow worked like a charm. Thank you very much. You can post this as an answer and I will accept that. –  Jun 05 '18 at 14:02

0 Answers0