I have the following response from an API
[[{\"message\":\"example message\"}]]
I tried to deserialize it as a list of lists as follow
public class ErrorMessage
{
[JsonProperty("message")]
public string Message;
}
public class ErrorMessages
{
public List<ErrorMessage> Messages;
}
public class ErrorMessagesList
{
public List<ErrorMessages> MessagesList;
}
The deserialization fails, how can I deserialize it?
This code works for me:
var someJson = "[[{\"message\":\"example message\"}]]";
var result = JsonConvert.DeserializeObject<List<List<ErrorMessage>>>(someJson);
Debug.Assert(result.First().First().Message == "example message");
You have a collection of a collection of instances of your ErrorMessage
class. In the code, I deserialize into a List of a List of ErrorMessage. So the first item in result is a List of ErrorMessage. The first item in that list is an ErrorMessage, and the Message
property of that object is "example message"
.
If your JSON looked like this, it would still deserialize with that DeserializeObject
call, but it would be more obvious what you were looking at:
var moreJson = @"[
[
{""message"": ""First message""},
{""message"": ""Second message""},
{""message"": ""Third message""}
],
[
{""message"": ""Fourth message""},
{""message"": ""Fifth message""}
]
]";
The List of list of ErrorMessage is more obvious in this code. But, it's the same type in both examples