如何在Controller中返回JSON格式的查询结果
问题修复与实现指南
以下是针对你的代码问题的分步修复方案,确保Controller能正确返回JSON格式的结果列表:
1. 修正接口与服务层的返回类型不匹配问题
当前接口IServices定义的CheckRecords返回IdIdentity,但数据服务层实际返回List<IdIdentity>,这会导致编译错误。
修正后的接口
public interface IServices { // 将返回类型改为List<IdIdentity> List<IdIdentity> CheckRecords(string guid); }
修正后的业务服务层
public static List<IdIdentity> CheckRecords(string guid) { return DataServices.Services.CheckRecords(guid); }
2. 修正Controller的类型接收与JSON返回
Controller当前错误地将结果接收为string类型,需要改为接收列表并直接返回JSON。
修正后的Controller
public JsonResult CheckData() { string guid = HttpContext.Request["GUID"]; // 接收List<IdIdentity>类型的结果 List<IdIdentity> result = Services.CheckRecords(guid); // 直接返回列表,ASP.NET会自动序列化为JSON return Json(result); }
3. 修复数据服务层的SQL与读取逻辑问题
当前数据服务层存在两处关键问题:
- 无用的空值检查(
IdIdentity Code = new IdIdentity();永远不会为null) - SQL查询仅返回
Name,但构造函数需要Id、Scheme和Name三个字段 - 读取器读取的列名与SQL返回字段不匹配
修正后的数据服务层
public class Services : IServices { public const string PARAM_FORM_GUID = "guid"; public List<IdIdentity> CheckRecords(string guid) { // 移除无用的空值检查 // 修正SQL,返回Id、Scheme、Name三个字段(需根据实际表结构调整列名) string sql= "SELECT Id, Scheme, Name FROM OCODE" + " WHERE SID IN(SELECT SID FROM OITEMS WHERE OITEM_ID IN (@" + PARAM_FORM_GUID + "))"; var parameters = new List<DbParameter> { CreateParameter(PARAM_FORM_GUID, DbType.String, guid, DBNull.Value), }; sql = ReplaceParameterPrefix(sql); return ReadAll(sql, parameters, reader => { // 读取SQL返回的对应字段,匹配构造函数参数 return new IdIdentity( reader.ReadByName("Id", string.Empty), reader.ReadByName("Scheme", string.Empty), reader.ReadByName("Name", string.Empty) ); }).ToList(); } }
4. 修正Model的语法错误
当前IdIdentity类存在无效的public语句,需要移除或补充完整。
修正后的Model
[Serializable] public class IdIdentity : GenericType { public string Id { get; set; } public string Scheme { get; set; } public string Name { get; set; } // 可选:添加无参构造函数,方便JSON序列化 public IdIdentity() { } public IdIdentity(string id, string scheme, string name = null) { Id = id; Scheme = scheme; Name = name; } }
额外注意事项
- 多GUID参数处理:如果传入的
guid是逗号分隔的多个GUID字符串,当前参数化查询无法直接支持IN子句,需要使用表值参数或拆分字符串的方式处理,否则会导致查询逻辑错误。 - JSON请求行为:如果是GET请求返回JSON,在旧版ASP.NET中可能需要添加
JsonRequestBehavior.AllowGet参数:return Json(result, JsonRequestBehavior.AllowGet);。
内容的提问来源于stack exchange,提问作者user21031522
相关产品推荐
相关产品推荐

