J Doe. J Doe. - 26 days ago 20
C# Question

Sum of nested object properties

I am wondering how I can get the sum of the JSON response:

I am trying to get the sum of Delivered so it would be 3435 + 20.

{[
{
"date": "2016-10-01",
"stats": [
{
"type": "subuser",
"name": "cooolguy@gmail.com",
"metrics": {
"blocks": 23,
"bounce_drops": 164,
"bounces": 19,
"clicks": 0,
"deferred": 412,
"delivered": 3435,
"invalid_emails": 27,
"opens": 0,
"processed": 3481,
"requests": 3675,
"spam_report_drops": 3,
"spam_reports": 0,
"unique_clicks": 0,
"unique_opens": 0,
"unsubscribe_drops": 0,
"unsubscribes": 0
}
}
]
},
{
"date": "2016-10-02",
"stats": [
{
"type": "subuser",
"name": "coolguy@gmail.com",
"metrics": {
"blocks": 0,
"bounce_drops": 0,
"bounces": 0,
"clicks": 0,
"deferred": 95,
"delivered": 20,
"invalid_emails": 0,
"opens": 0,
"processed": 0,
"requests": 0,
"spam_report_drops": 0,
"spam_reports": 0,
"unique_clicks": 0,
"unique_opens": 0,
"unsubscribe_drops": 0,
"unsubscribes": 0
}
}
]
}
]}


Would I do something like this? I have tried doing this but it doesn't work I will get the error:


Additional information: Cannot perform runtime binding on a null
reference


string getresponse;

getresponse = response.Body.ReadAsStringAsync().Result;

string s = getresponse;

dynamic o = JsonConvert.DeserializeObject(s);

textBox1.Text = o[0].stats[0].metrics[0].delivered;

Answer

metrics property is a dictionary, that's why you need to access it's values by a key.

dynamic result = JsonConvert.DeserializeObject<dynamic>(jsonString);
var res = result[0].stats[0].metrics["delivered"];

Finished edit: You have to create classes to properly deserialize that json.

    public class Rootobject
    {
        public string date { get; set; }
        public Stat[] stats { get; set; }
    }

    public class Stat
    {
        public string type { get; set; }
        public string name { get; set; }
        public Metrics metrics { get; set; }
    }

    public class Metrics
    {
        public int blocks { get; set; }
        public int bounce_drops { get; set; }
        public int bounces { get; set; }
        public int clicks { get; set; }
        public int deferred { get; set; }
        public int delivered { get; set; }
        public int invalid_emails { get; set; }
        public int opens { get; set; }
        public int processed { get; set; }
        public int requests { get; set; }
        public int spam_report_drops { get; set; }
        public int spam_reports { get; set; }
        public int unique_clicks { get; set; }
        public int unique_opens { get; set; }
        public int unsubscribe_drops { get; set; }
        public int unsubscribes { get; set; }
    }

After that you can get the sum like this:

var result = JsonConvert.DeserializeObject<List<Rootobject>>(jsonString);
var sum = result.SelectMany(x => x.stats).Sum(x => x.metrics.delivered);
Comments