skip to Main Content

I am receiving a response from API in below string format:

"{"nbf":2024-04-17T16:28:14.509+0800, "iat":2024-04-17T16:28:14.509+0800, "iss":"https://google.com" }"

When I am trying to use JObject.Parse() method then I am getting below error:

"Unexpected character encountered while parsing number: T. Path ‘nbf’"

2

Answers


  1. The property nbf appears to have the value that is a ISO date time; but JSON has no support for date time values.

    Such a date time needs to be serialised as a string (ie. in double quotes).

    Likely the invalid character is the first - because the prior characters in the value would otherwise be a number,.

    For the full details of the JSON format see https://www.rfc-editor.org/rfc/rfc8259 section 3.

    Login or Signup to reply.
  2. your best approach is to insert " before serializing.
    P.S. I wrote fast, code can be refactored for better…

    void Main()
    {
        string json = "{"nbf":2024-04-17T16:28:14.509+0800, "iat":2024-04-17T16:28:14.509+0800, "iss":"https://google.com" }";
        json = FixJson(json);
        JsonSerializerSettings settings = new JsonSerializerSettings
        {
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
            Formatting = Newtonsoft.Json.Formatting.Indented
        };
        JsonConvert.DeserializeObject<Test>(json).Dump();
    }
    
    string FixJson(string j)
    {
        j = ReplaceValue(j, "nbf", 28);
        j = ReplaceValue(j, "iat", 28);
        return j.ToString();
    }
    
    public string ReplaceValue(string s, string value, int len)
    {
        var sb = new StringBuilder();
        int startposition = s.IndexOf(value)+5;
        sb.Append(s.Substring(0, startposition));
        sb.Append($""{s.Substring(startposition, len)}"");
        var last = s.Substring(startposition + len);
        sb.Append(last);
        return sb.ToString();
    }
    
    public class Test
    {
        public DateTimeOffset nbf { get; set; }
        public DateTimeOffset iat { get; set; }
        public string iss { get; set; }
    
    }
    
    

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search