Search code examples
c#jsondeserialization

Convert String to Decimal in Dynimc json


I have a dynamic json string:

[{
  "Id": "1",
  "Description": "Scenario 1",
  "fc": "-45156,60000",
  "fci": "-45156,60000",
  "fcii": null,
  "fciii": null,
  "fciv": null,
},
{
  "Id": "1",
  "Description": "Scenario 2",
  "fc": "-45156,60000",
  "fci": "-45156,60000",
},
{
  "Id": "1",
  "Description": "Scenario 3",
  "fc": "-45156,60000",
  "fci": "-45156,60000",
  "fcii": null,
},
{
  "Id": "1",
  "Description": "Scenario 4",
  "fc": "-45156,60000",
}]

is it a good idea to search in json object for string that contains , an idea

    public decimal ConvertToDecimal(string s)         
    {             
        if (s.Contains(','))             
        {                 
            return decimal.Parse(s.Replace(',', '.'));             
        }             
        else                  
            return SomeDecimalValue;         
     }

How I can parse the string to Decimal and keep the decimal separator?


Solution

  • you can try this code

        var jArr = JArray.Parse(json);
    
        foreach (var item in jArr)
        {
            foreach (var prop in ((JObject)item).Properties())
            {
    if (prop.Name=="Id" || prop.Name=="Description") continue; //you can remove it
                var val = ConvertToDecimal((string)prop.Value);
                if (val != null) prop.Value = val;
            }
        }
    
          json = jArr.ToString();
    
    public decimal? ConvertToDecimal(string s)
    {
        if (!string.IsNullOrEmpty(s))
            if (decimal.TryParse(s.Replace(',', '.'), out var val))
                return val;
        return null;
    }
    

    Since nobody knows what value fc is - is it one number, or two you can change ConvertToDecimal accordingly.

    Or you can deserialize it using c# class

    List<Forecast> forecast= jArr.ToObject<List<Forecast>>();
    
    public class Forecast
    {
        public int Id { get; set; }
        public string Description { get; set; }
    
        [JsonExtensionData]
        public Dictionary<string, object> Extra { get; set; }
    }