嵌套对象属性的总和
本文关键字:属性 对象 嵌套 | 更新日期: 2023-09-27 18:16:47
我想知道如何获得JSON响应的总和:
我正试图得到Delivered的总和,所以它将是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
}
}
]
}
]}
我能做这样的事吗?我试过这样做,但它不起作用,我会得到错误:
附加信息:无法对null执行运行时绑定参考
string getresponse;
getresponse = response.Body.ReadAsStringAsync().Result;
string s = getresponse;
dynamic o = JsonConvert.DeserializeObject(s);
textBox1.Text = o[0].stats[0].metrics[0].delivered;
metrics
属性是一个字典,这就是为什么您需要通过键访问它的值。
dynamic result = JsonConvert.DeserializeObject<dynamic>(jsonString);
var res = result[0].stats[0].metrics["delivered"];
完成编辑:您必须创建类来正确地反序列化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; }
}
之后你可以得到这样的总和:
var result = JsonConvert.DeserializeObject<List<Rootobject>>(jsonString);
var sum = result.SelectMany(x => x.stats).Sum(x => x.metrics.delivered);
public class Metrics
{
public int delivered { get; set; }
}
public class Stat
{
public Metrics metrics { get; set; }
}
public class RootObject
{
public List<Stat> stats { get; set; }
}
List<RootObject> o = JsonConvert.DeserializeObject<List<RootObject>>(json);
var result = o.Sum(x => x.stats.Sum(y => y.metrics.delivered));