假设我有这个jarray:
{
"ArrayofItem":{
"Item":[
{
"Amount": "1.52"
"Date": "05/01/2015"
},
{
"Amount": "2.52"
"Date": "05/01/2015"
},
{
"Amount": "5.62"
"Date": "05/02/2015"
},
{
"Amount": "1.06"
"Date": "05/02/2015"
},
{
"Amount": "6.30"
"Date": "05/03/2015"
},
{
"Amount": "1.00"
"Date": "05/04/2015"
},
{
"Amount": "1.55"
"Date": "05/04/2015"
},
{
"Amount": "1.63"
"Date": "05/05/2015"
},
{
"Amount": "1.78"
"Date": "05/06/2015"
}
}
}
我如何合并这些项目,以便将同一日期的所有项目组合在一起以创建一个新的jarray:
{
"ArrayofItem":{
"Item":[
{
"Amount": "4.04"
"Date": "05/01/2015"
},
{
"Amount": "6.68"
"Date": "05/02/2015"
},
{
"Amount": "6.30"
"Date": "05/03/2015"
},
{
"Amount": "2.55"
"Date": "05/04/2015"
},
{
"Amount": "1.63"
"Date": "05/05/2015"
},
{
"Amount": "1.78"
"Date": "05/06/2015"
}
}
}
本质上,我需要按原始项目的日期列表进行总结。您可以假设项目已经按日期进行排序。
如果要纯粹与linq到JSON进行此操作,则可以使用GroupBy
和Sum
创建必要的对象:
var obj = JObject.Parse(json);
var query = obj.SelectTokens("ArrayofItem.Item")
.SelectMany(t => t)
.OfType<JObject>()
.GroupBy(o => o["Date"], o => o["Amount"])
.Select(g => new JObject(new JProperty("Amount", g.Sum(a => (decimal)a)), new JProperty("Date", g.Key)));
var newObj = new JObject(new JProperty("ArrayofItem", new JObject(new JProperty("Item", new JArray(query)))));
您可以将下面的代码用作模型:
public class Rootobject
{
public Arrayofitem ArrayofItem { get; set; }
}
public class Arrayofitem
{
public Item[] Item { get; set; }
}
public class Item
{
public string Amount { get; set; }
public string Date { get; set; }
}
然后,此代码将完成工作:
string jsonText = "your json text goes here...";
var o = JsonConvert.DeserializeObject<Rootobject>(jsonText);
var itemArray = o.ArrayofItem.Item
.GroupBy(item => item.Date, (date, item) =>
new Item
{
Date = date,
Amount = item.Sum(i => float.Parse(i.Amount)).ToString()
}).ToArray();
string serializedGroup = JsonConvert.SerializeObject(new Rootobject { ArrayofItem = new Arrayofitem { Item = itemArray } });