1111lt
1111lt

Reputation: 35

JSON output needs to in the right format

I have an issue where my Majors object is not serializing correctly to JSON. It needs to look like this, a string array:

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

Instead it looks like this

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

Here is what I have so far:

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

Any suggestions please? Thanks!

Upvotes: 0

Views: 55

Answers (1)

Joe Steele
Joe Steele

Reputation: 691

I think it's because you're projecting into a new Majors object in your select statement rather than just taking the Major value itself.

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

Instead of

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

Upvotes: 1

Related Questions