实体类序列化为 json

本文关键字:json 序列化 实体 | 更新日期: 2023-09-27 18:35:43

       try
        {
            using (EXAMINATIONEntities entity = new EXAMINATIONEntities())
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                var exams = entity.TBL_EXAMS.Where(x => x.USERID == userId);                    
                return serializer.Serialize(exams);
            }
        }
        catch (Exception ex)
        {
            return "-1";
            throw ex;
        }

此代码工作正常。但是返回一个这样的 json 字符串;

[{"EXAM_ID":1,"EXAM_TEXT":"sdf","EXAM_ORDER":1,"SITUATION":true,"USERID":100,"DBDATETIME":null,"TBL_QUESTIONS":[],"EntityState":2,"EntityKey":{"EntitySetName":"TBL_EXAMS","EntityContainerName":"EXAMEntities","EntityKeyValues":

我只想序列化表字段:"EXAM_ID":1,"EXAM_TEXT":"sdf","EXAM_ORDER":1,"SITUATION":true,"USERID":100,"DBDATETIME":null

但它会破坏所有实体类字段和属性。如何序列化要序列化的实体类字段?

实体类序列化为 json

只能将所需的属性投影到匿名类型:

JavaScriptSerializer serializer = new JavaScriptSerializer();
var exams = entity.TBL_EXAMS.Where(x => x.USERID == userId)
           .Select(exam => new {
                      exam.EXAM_ID, exam.EXAM_TEXT, exam.EXAM_ORDER /* etc */
                   });                    
return serializer.Serialize(exams);