如何从数据列表创建json结构?

时间:2016-04-05 10:20:14

标签: c# .net json linq asp.net-web-api

我想用列表对象中的嵌套对象创建json结构。

这是我的班级:

public class Employee
{
     public int EmployeeId { get; set; }
     public int Skillssetpoints { get; set; }
     public string Name { get; set; }
     public Nullable<System.DateTime> Date { get; set; }
}

public class EmployeeModel
{
     public int EmployeeId { get; set; }
     public List<int> Skillssetpoints { get; set; }
     public string Name { get; set; }
     public Nullable<System.DateTime> Date { get; set; }
}

记录是这样的:

EmployeeId   SkillssetPoints   Date
 1              10             4/5/2016 16:12:12
 2              12             3/5/2016 17:12:12
 3              4              8/5/2016 8:12:12
 4              20             1/5/2016 2:12:12

这就是我获取数据的方式:

var data=context.Employee.Tolist();

获取数据后,我想使用EmployeeModel从上面的数据创建此 json结构并返回:

预期输出:

 {"Date":"8-5-2016 08:12:12","SkillssetPoints":[4,10,12,20]}

在日期字段中,我将采用最高日期,因此8-5-2016 SkillssetPoints 将按升序排序。

如何使用 EmployeeModel 类创建此json结构?

7 个答案:

答案 0 :(得分:4)

添加对nuget包的引用Newtonsoft.Json然后使用...

string result = JsonConvert.Serialize(data); 

看起来您需要先将数据转换为模型格式,然后先进行投影,然后序列化结果......

var groupedData = data
    .GroupBy(s => s.EmployeeId)
    .OrderBy(s => s.Date)
    .Select(g => new EmployeeModel {
        EmployeeId = g.Key,
        Name = g.First().Name,
        Date = g.First().Date,
        Skillssetpoints = g.Select(s => s.Skillssetpoints).OrderBy(i => i).ToList()
    });

那应该产生这个模型的集合......

public class EmployeeModel
{
    public int EmployeeId { get; set; }
    public List<int> Skillssetpoints { get; set; }
    public string Name { get; set; }
    public DateTime? Date { get; set; }
}

......当我这样做时......

var data = new List<EmployeeModel> {
    new EmployeeModel { EmployeeId = 1, Name = "Homer Simpson", Skillssetpoints = new List<int> { 1,2,3,4 }, Date = DateTime.Now },
    new EmployeeModel { EmployeeId = 2, Name = "Marge Simpson", Skillssetpoints = new List<int> { 1,2,3,4 }, Date = DateTime.Now },
    new EmployeeModel { EmployeeId = 3, Name = "Lisa Simpson", Skillssetpoints = new List<int> { 1,2,3,4 }, Date = DateTime.Now },
    new EmployeeModel { EmployeeId = 4, Name = "Bart Simpson", Skillssetpoints = new List<int> { 1,2,3,4 }, Date = DateTime.Now }
};

var result = JsonConvert.SerializeObject(data);

我得到了这个输出......

[
    {
        "EmployeeId": 1,
        "Skillssetpoints": [1,2,3,4],
        "Name": "Homer Simpson",
        "Date": "2016-04-05T11:42:09.9126748+01:00"
    },
    {
        "EmployeeId": 2,
        "Skillssetpoints": [1,2,3,4],
        "Name": "Marge Simpson",
        "Date": "2016-04-05T11:42:09.9126748+01:00"
    },
    {
        "EmployeeId": 3,
        "Skillssetpoints": [1,2,3,4],
        "Name": "Lisa Simpson",
        "Date": "2016-04-05T11:42:09.9126748+01:00"
    },
    {
        "EmployeeId": 4,
        "Skillssetpoints": [1,2,3,4],
        "Name": "Bart Simpson",
        "Date": "2016-04-05T11:42:09.9126748+01:00"
    }
]

答案 1 :(得分:2)

通过对特定字段进行分组来选择所需记录,然后以所需模式准备匿名对象并将其序列化以获得最终结果,

        var models = (from em in employeeModels
                      group em by em.ID into g
                      select new
                      {
                          Id = g.Key,
                          maxDate = g.Max(p => p.Date)
                      }).ToList();
        var result = new
        {
            date = prices.Max(p => p.maxDate),
            SkillssetPoints = prices.Select(p => p.Id).ToList()
        };

        var json = JsonConvert.SerializeObject(result);

您将获得类似

的模式中的json
{
    "date": "2016-04-05T16:39:54.8420979+05:30",
    "SkillssetPoints": [
        1,
        2,
        3
    ]
}

答案 2 :(得分:2)

您可以尝试创建一个新对象并按以下序列化:

var result = JsonConvert.Serialize (new {
    Date = context.Employee.Max(e => e.Date),
    SkillssetPoints = context.Employee.Select(e => e.SkillssetPoints)
}));

答案 3 :(得分:2)

使用newton JSON,它可以在NuGet上使用,代码非常简单。

using Newtonsoft.Json;

var jsonList = JsonConvert.SerializeObject(context.Employee.Tolist());

干杯

答案 4 :(得分:2)

使用Nuget Package中的Newton JSON并尝试此代码

列出lstEmp = new List();

        for (int i = 1; i <= 4; i++)
        {
            Employee emp = new Employee();
            emp.EmployeeId = i;
            emp.Name = "Name" + i;
            emp.Skillssetpoints = i + 1;
            emp.Date = DateTime.Now.AddDays(i);
            lstEmp.Add(emp);
        }

        var data = lstEmp;
        var result = new EmployeeModel
        {
            Date = data.Max(p => p.Date),
            Skillssetpoints = data.Select(p => p.Skillssetpoints).ToList()
        };

        var JsonData = JsonConvert.SerializeObject(new
        {
            Date = result.Date,
            Skillssetpoints = result.Skillssetpoints
        });

干杯

答案 5 :(得分:2)

1)使用NuGet

安装Newtonsoft.Json包

2)在顶部添加名称空间

 using Newtonsoft.Json;

3)在不希望包含在json转换中的Model类属性上添加[JsonIgnore]

 public class Employee
{
    public int EmployeeId { get; set; }
    public int Skillssetpoints { get; set; }
    public string Name { get; set; }
    public Nullable<System.DateTime> Date { get; set; }
}

public class EmployeeModel
{
    [JsonIgnore]
    public int EmployeeId { get; set; }
    public List<int> Skillssetpoints { get; set; }
    [JsonIgnore]
    public string Name { get; set; }
    public Nullable<System.DateTime> Date { get; set; }
}

4)最终代码在

之下
var data = new List<Employee>();
        data.Add(new Employee { EmployeeId = 1, Skillssetpoints = 10, Date = Convert.ToDateTime("4/5/2016 16:12:12") });
        data.Add(new Employee { EmployeeId = 2, Skillssetpoints = 12, Date = Convert.ToDateTime("3/5/2016 17:12:12") });
        data.Add(new Employee { EmployeeId = 3, Skillssetpoints = 4, Date = Convert.ToDateTime("8/5/2016 8:12:12") });
        data.Add(new Employee { EmployeeId = 4, Skillssetpoints = 20, Date = Convert.ToDateTime("1/5/2016 2:12:12") });

        var highestDate = data.OrderByDescending(e => e.Date).First().Date;
        var skillssetpointsList = data.Select(e => e.Skillssetpoints).ToList();


        EmployeeModel employeeModel = new EmployeeModel()
        {
            Date = highestDate,
            Skillssetpoints = skillssetpointsList
        };

        string jsonString = JsonConvert.SerializeObject(employeeModel);

现在,jsonString = {“Skillssetpoints”:[10,12,4,20],“Date”:“2016-05-08T08:12:12”}

答案 6 :(得分:1)

我想你可以尝试一下 它适用于我。

public ActionResult GetCitiesWithBranches(int regionID)
    {
        var cities =
            _context.Cities.Where(e => e.RegionCode == regionID)
                .Select(e => new { ID = e.CityCode, Name = e.Name })
                .ToList();
        return Json(new { cities = cities });
    }

在我使用的视图中:

var json = { regionID: data };
$.ajax({
            type: "POST",
            url: '@Url.Action("GetCitiesWithBranches", "Admin")',
            data: json,
            dataType: "json",
            error: function (xhr, status, error) {
                //alert("error routine");
            },
            success: function (res) {                    
                if (res.cities) {

                }
            }
        });

希望这会有所帮助..