序列化为JSON

时间:2017-12-14 09:33:26

标签: c# json model-view-controller serialization

this is my sql result

我希望将结果序列化为json 喜欢以下

import {Component, OnInit} from '@angular/core';
import {User} from '../../models/user.model';
import {ActivatedRoute} from '@angular/router';

@Component({
    selector: 'app-profile',
    templateUrl: './profile.component.html',
    styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {

    user: User;

    constructor(private route: ActivatedRoute) {
    }

    ngOnInit() {
        this.user = this.route.snapshot.data['profile'];
        console.log('user', this.user);
    }

}

如何在mvc api中将sql结果序列化为json,我已经在使用newtonsoft来序列化其他结果,使用LINQ是更好的方法吗?如果是的话怎么样?

my code Looks like

1 个答案:

答案 0 :(得分:1)

我不知道有哪些库会自动为您完成,但您当然可以编写类似以下内容的代码:

        var grouped = results.GroupBy(r => r.StudentID).Select(g => new
        {
            StudentID = g.Key,
            ExamTypes = g.GroupBy(r => r.ExamType).Select(g2 => new
            {
                ExamType = g2.Key,
                ExamNames = g2.GroupBy(r => r.ExamName).Select(g3 => new
                {
                    ExamName = g3.Key,
                    SubjectNames = g3.GroupBy(r => r.SubjectName).Select(g4 => new
                    {
                        SubjectName = g4.Key,
                        SubComponents = g4.Select(r => new { SubjectComponentName = r.SubjectComponentName, ExamDate = r.ExamDate, MaxMark = r.MaxMark, MarkObtained = r.MarkObtained /* others here */ })
                    })
                })
            })
        });

        var serialized = Newtonsoft.Json.JsonConvert.SerializeObject(grouped);

请注意,我已经复制了其值为集合的属性的名称,但是如果您需要保持指定的确切属性名称,则可以很容易地更改它。