Home > Back-end >  how to fix Deserialise object ignoring 0 in the starting of the number , but i want 0 to be as it is
how to fix Deserialise object ignoring 0 in the starting of the number , but i want 0 to be as it is

Time:10-11

var crmData = (JObject)JsonConvert.DeserializeObject(metaData.MetaData);

in above expression

metaData.MetaData contains correct values from UI as shown below

metaData.MetaData = "{ ApplicationFields : { folderId : 3633, reasonCodes: [01,02] }}"

but after JsonConvert the crmData contains below value

crmData = {{
  "ApplicationFields": {
    "folderId": 3633,
    "reasonCodes": [1,2]
  }
}}

as you can see reasonCodes values has been converted from 01 to 1 and 02 to 2.

how to avoid conversion. i want same values in crmData also.

CodePudding user response:

It's not clear why you care about those leading zeros. As pointed out in the comments they are meaningless when using numbers. So if you really need them, change the JSON to use strings instead:

reasonCodes: ["01", "02"]

Alternatively, deserialise into a proper C# class and define the type as string:

public class Root
{
    public Foo ApplicationFields { get; set; }  
}

public class Foo
{
    public int FolderId { get; set; }
    public string[] ReasonCodes { get; set; }
}

And deserialise like this:

var result = JsonConvert.DeserializeObject<Root>(Json); 

Console.WriteLine(string.Join(", ", result.ApplicationFields.ReasonCodes));
//Output:
//  01, 02

CodePudding user response:

A leading zero is invalid for numbers in in JSON:

number = [ minus ] int [ frac ] [ exp ]
[...]
int = zero / ( digit1-9 *DIGIT )

You can have either a zero or a non-zero starting digit in a number. You might be able to solve this by using a custom converter.

  • Related