c# - 如何在 C# 中按 ID 对 JSON 数据进行分组
问题描述
将数据表中的数据序列化后获取这种格式的JSON
这是读取excel文件并将数据存储在数据表中后的结果。后来使用 newtosoft.json 序列化到下面的 JSON 输出中
JSON现在低于:
[{ "Id": "1", "Profit": "33.332999999999998", "Telephone": "123", "Email": "user1@testmail.com" }, { "Id": "1", "Profit": "21.21", "Telephone": "43", "Email": "user11@testmail.com" }, { "Id": "2", "Profit": "49.000999999999998", "Telephone": "22", "Email": "user2@testmail.com" }, { "Id": "2", "Profit": "10.1", "Telephone": "876", "Email": "user22@testmail.com" }]
预期格式
[{ "Id": "1", "Profits": ["33.332999999999998", "21.21"], "Telephones": ["43", "123"], "Emails": ["user1@testmail.com", "user11@testmail.com"] }, { "Id": "2", "Profits": ["49.000999999999998", "10.1"], "Telephones": ["876", "22"], "Emails": ["user2@testmail.com", "user22@testmail.com"] }]
有人可以帮忙吗?
解决方案
尝试这个
var json=...origin json
var jD = JsonConvert.DeserializeObject<DataOrigin[]>(json);
jD=jD.OrderBy(d => d.Id).ToArray();
var prevId=string.Empty;
var list=new List<Data>();
foreach (var item in jD)
{
if(item.Id!=prevId)
{
prevId=item.Id;
list.Add(new Data(Convert.ToInt32(item.Id), item.Profit, item.Telephone, item.Email));
}
else
{
var prevIdInt=Convert.ToInt32(prevId);
var prevItem=list.Last(l =>l.Id==prevIdInt );
prevItem.MergeItem(item.Profit,item.Telephone,item.Email);
}
}
var result = JsonConvert.SerializeObject(list);
结果
[
{
"Id": 1,
"Profits": [
33.333,
21.21
],
"Telephones": [
"123",
"43"
],
"Emails": [
"user1@testmail.com",
"user11@testmail.com"
]
},
{
"Id": 2,
"Profits": [
49.001,
10.1
],
"Telephones": [
"22",
"876"
],
"Emails": [
"user2@testmail.com",
"user22@testmail.com"
]
}
]
班级
public class DataOrigin
{
public string Id { get; set; }
public double Profit { get; set; }
public string Telephone { get; set; }
public string Email { get; set; }
}
public class Data
{
public int Id { get; set; }
public List<double> Profits { get; set; }
public List<string> Telephones { get; set; }
public List<string> Emails { get; set; }
public Data(int id,double profit,string phone, string email)
{
Id=id;
Profits = new List<double>(){profit};
Telephones = new List<string>(){phone};
Emails = new List<string>(){email};
}
public void MergeItem (double profit,string phone, string email)
{
Profits.Add(profit);
Telephones.Add(phone);
Emails.Add(email);
}
}
推荐阅读
- android - Flutter CameraPreview() 高度和宽度自定义
- java - 为什么在自定义 AbstractR2dbcConfiguration 的情况下注解 @Transactional 不起作用
- google-cloud-dataflow - 是否可以触发具有 GroupByKey 或 CombineFn 的每个键的写入?
- javascript - 使用 .filter 获取我选择的元素的索引
- c# - 将数据表导出到多语言内容的 Excel
- c++ - LibHaru 库出现问题
- snowflake-cloud-data-platform - Snowflake 过程中 While 循环中的 IF 条件
- microsoft-forms - 我如何知道是否有人回答了排序顺序 MS Forms 问题或只是保留了默认顺序?
- javascript - 滚动到部分时更改 URL
- android - ImageView 适合有限空间并保持相同的缩小比例