首页 > 解决方案 > 如何在 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"] }]

有人可以帮忙吗?

标签: c#json.net

解决方案


尝试这个

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);
    }
}

推荐阅读