'Deep count for object properties
I'd like to count the number of properties within an object. I have found several solutions but none really counts the child\nested propertie.
For instance, I have the following JSON object.
{
"id": "259a36d2-3852-425f-a70c-3f9477753210",
"name": "foo",
"type": "na",
"text": "ABC.pdf",
"left": 333,
"top": 130,
"w": 134,
"h": 34,
"customData": {
"A": "fa6css4ec8-8ffb-55bca4dde06a",
"name": "SDF.pdf",
"IsExists": false,
"PNumber": 1,
}
}
When trying the following I'm getting the result of 9, while I'm expecting 12 (which is the count of the entire properties).
JObject sourceJObject = JsonConvert.DeserializeObject<JObject>(json);
var res= sourceJObject.Count;
I'll be happy for assistant.
Solution 1:[1]
try this
var obj=JObject.Parse(json);
var count=0;
CountProps(obj, ref count); // count=12
public void CountProps(JToken obj, ref int count)
{
if (obj is JObject)
foreach (var property in ((JObject)obj).Properties())
{
if (property.Value is JValue) count++;
if (property.Value is JObject) CountProps(property.Value, ref count);
if (property.Value is JArray) { count++; CountProps(property.Value, ref count); }
}
if (obj.GetType().Name == "JArray")
foreach (var property in ((JArray)obj))
if (property is JObject || property is JArray) CountProps(property, ref count);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
