Reputation: 370
I know there are a lot of questions out there about this topic but I can't seem to find one that fits what I'm seeing. I've tried cleaning the string, swapping double quotes with single quotes, removing the escape chars, trimming the beginning and the end but nothing seems to work.
The following is a real basic code snippet (Yes I know I'm trying to deserialize from a string into a string but it's just a proof of concept to try and figure out why the string cannot be deserialized to begin with).
JSON:
{
"notifications": [
{
"id": "test",
"type": "test type",
"timestamp": "2022-02-14T21:27:44+0000"
}
]
}
And the proof of concept code:
try
{
var str = "{\"notifications\":[{\"id\":\"test\",\"type\":\"test type\",\"timestamp\":\"2022-02-14T21:27:44+0000\"}]}";
var tempAns = JsonConvert.DeserializeObject<string>(str);
Console.WriteLine(tempAns);
}
catch (Exception ex)
{
Console.ReadLine();
}
The above throws the following exception:
Unexpected character encountered while parsing value: {. Path '', line 1, position 1.
Can anyone explain to me why and/or how to resolve this?
Upvotes: 1
Views: 1321
Reputation: 43880
You have to create classes for each object in the JSON data you want to deserialize.
Start with deserializing the root object:
var tempAns = JsonConvert.DeserializeObject<Root>(str);
And write classes for both the root object (which contains an array, hence the List
data type) and the array object's properties:
public class Notification
{
public string id { get; set; }
public string type { get; set; }
public DateTime timestamp { get; set; }
}
public class Root
{
public List<Notification> notifications { get; set; }
}
Upvotes: 5