Home > Blockchain >  Preserving trailing zeros when selecting values from Json String using Newtonsoft
Preserving trailing zeros when selecting values from Json String using Newtonsoft

Time:03-12

I have a third party api that I need to test and need to ensure that the values returned are the exact values sent in the response. For example if a number is returned as 1.000 it needs to be 1.000 and not 1.

I have tried deserializing the string response to a JObject and selecting values into a JToken, but the value for obj1.n2 below ends up being 1. I almost want to select the raw value at a specific path as a string, regardless of the type.

Is there a way using Json.Net I can select obj1.n2 from a string representation of the example below and preserve the trailing zeros?

For example:

{ "obj1": [{ "n1": "n", "n2": 1.000, "n3": true }, { "n1": "n", "n2": 10.000, "n3": false }] }

CodePudding user response:

Because C# decimal types preserve trailing zeros, you can just instruct Json.Net to parse numbers to decimals instead of floating points. Do this by setting FloatParseHandling to FloatParseHandling.Decimal as shown here:

var json = @"{ ""obj1"": [{ ""n1"": ""n"", ""n2"": 1.000, ""n3"": true }, { ""n1"": ""n"", ""n2"": 10.000, ""n3"": false }] }";

var token = JsonConvert.DeserializeObject<JToken>(
    json, 
    new JsonSerializerSettings { FloatParseHandling = FloatParseHandling.Decimal });

token["obj1"][0]["n2"] will now show 1.000 instead of 1.

  • Related