Home > Blockchain >  C# Json Deserialization into string throws exception: "Unexpected character encountered while p
C# Json Deserialization into string throws exception: "Unexpected character encountered while p

Time:02-15

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 POC to try and figure out why the string cannot be deserialized to begin with).

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?

CodePudding user response:

you have to create classes if you want to deserialize

var tempAns = JsonConvert.DeserializeObject<Root>(str);

classes

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; }
    }
  • Related