Search code examples
c#jsoncouchbasecouchbase-lite

C#: In an object is it possible to convert decimal values to a string or double?


I have a Json object which I get from rest call and there is no specific format. Is it possible to iterate through the object and check if any decimal value exists and convert it to a string/double?

I need to pass this object into a couchbaseLite's MutableDocument which doesn't allow any decimals

Object

{
 "performer": [
    {
      "referedBy": "ABDC",
      "text": "XYZ"
    }
  ],
  "quantity": {
    "value": 100.0, **// --> This should bee converted to "100.0"**
    "system": "http://unitsofmeasure.org",
  },
"range": [
    {
      "low": {
        "value": 0.0, **// --> This should bee converted to "0.0"**
        "system": "http://unitsofmeasure.org",
      },
      "text": "Total values"
    }
  ]
}

I tried to do it by checking the specific properties and fixing it i.e., check for "quantity", "range" etc. But wondering if there is a better way to iterate through the object i.e., a generic method that can iterate through the object that can convert the decimals to integer/double as I won't know the exact format of the object beforehand.

Code:

private static void UpdateQuantity(JToken result)
        {
            var quantity = (result as JToken)["quantity"];
            if (quantity == null)
            {
                return;
            }
            //update value from deciaml to string in quantity
            string quantityValue = null;
            foreach (JToken token in (result as JToken)["quantity"].Children())
            {
                JProperty ps = token as JProperty;
                if (ps != null && ps.Name.Contains("value"))
                {
                    quantityValue = ps.Value.ToString().Replace(',', '.');
                    ps.Replace(new JProperty("value", quantityValue as object));
                    break;
                }
            }
        }

Solution

  • The following code should work for you

    foreach (var token in
        obj.DescendantsAndSelf().OfType<JObject>().SelectMany(o =>
            o.Properties().Where(p => p.Value.Type == JTokenType.Integer || p.Value.Type == JTokenType.Float)))
    {
        token.Value = token.Value.ToString();
    }
    

    dotnetfiddle

    • Take all descendants of the root object, including itself.
    • Which are JObject
    • Select all their properties where...
    • ... the JSON type of the property value is either Integer or Float
    • For each one, change the value to be the stringified form of the same value.