JSON输出需要采用正确的格式

时间:2015-07-01 13:54:03

标签: c# json linq

我遇到一个问题,我的Majors对象没有正确地序列化为JSON。它需要看起来像这样一个字符串数组:

   "academics": {
                "majors": [
           “BS”, “MS”…etc
]}

相反,它看起来像这样

    "academics": {
                "majors": [
                          {"Major":"BS"},
                          {“Major”:”MS”}
                          ]}

这是我到目前为止所做的:

  public class Student
    {
        public string StudentId { get; set; }
        public string Gender { get; set; }
        public Academics academics { get; set; }  
    }

    public class Academics
    {
        public List<Majors> majors { get; set; }        
    }
    public class Majors
    {
        public string Major { get; set; }
    }


    public List<Student> GetStudentData()
    {
        List<Student> dataStudent;
        using (IDbConnection connection = RepositoryHelper.OpenConnection())
        {
            dataStudent = connection.Query<dynamic>(
                "mystoredprocedure", 
                commandType: CommandType.StoredProcedure)
                    .GroupBy(x => x.StudentId)
                    .Select(x => new Student 
                        { 
                            StudentId = x.First().StudentId, 
                            Gender = x.First().Gender,
                            academics = (new Academics
                                {
                                    majors = x.Select(ea => new Majors
                                    {
                                        Major = ea.Major
                                    }).ToList()
                                })
                            }).ToList();      

            return dataStudent;
        }
    }

有什么建议吗?谢谢!

1 个答案:

答案 0 :(得分:1)

我认为这是因为你在select语句中投射到一个新的Majors对象,而不仅仅是采用Major值。

majors = x.select(ea => new Majors { Major = ea.Major }).ToList()

而不是

majors => x.select(ea => ea.Major)