Search code examples
c#json.netserializationlogic

Newtonsoft Serialize: strings with leading zeros


I have a short question:

Why does this work

Newtonsoft.Json.JsonConvert.DeserializeObject<string>("768")

But this not

Newtonsoft.Json.JsonConvert.DeserializeObject<string>("0768")

Solution

  • in Json string should have 2 sets of "", try this

    string s= Newtonsoft.Json.JsonConvert.DeserializeObject<string>("\"0768\""); // 0768
    

    if it has one set only, json deserializes string as number

    int i= JsonConvert.DeserializeObject<int>("768"); //768
    

    but for some reasons, any number that starts from zero causes an exception

    int i= JsonConvert.DeserializeObject<int>("0768"); 
    

    and it is a well known bug that is in Json documentation

    but if you try this, you will get an exception

    string s= JsonConvert.DeserializeObject<string>("abc")
    

    this is ok

    string s= JsonConvert.DeserializeObject<string>("\"abc\""); //abc