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, “状况”:真 “USERID”:100, “DBDATETIME”:NULL, “TBL_QUESTIONS”:[], “EntityState”:2 “的EntityKey”:{ “EntitySetName”: “TBL_EXAMS”, “EntityContainerName”: “EXAMINATIONEntities”, “EntityKeyValues”:
我想序列化表字段:“EXAM_ID”:1,“EXAM_TEXT”:“sdf”,“EXAM_ORDER”:1,“SITUATION”:true,“USERID”:100, “DBDATETIME”:空
但它会对所有实体类字段和属性进行系列化。如何序列化我想要串行化的实体类字段?
答案 0 :(得分:2)
您只能将您想要的属性投影为匿名类型:
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);