MVC使用Newtonsoft无需实体类,实现JSON数据返回给前端页面使用
程序员文章站
2024-01-03 11:31:58
...
//引用using Newtonsoft.Json; using Newtonsoft.Json.Linq;
public ActionResult JsonSample()
{
ResponseResult obj = new ResponseResult();
try
{
JObject jo = new JObject();
jo.Add("UserName", "张三");
jo.Add("Sex", "男");
jo.Add("Age", 20);
jo.Add("Money", 10060);
jo.Add("Address", "深圳市南山区");
obj.info = jo;
obj.status = true;
obj.message = "获取信息成功";
}
catch (Exception ex)
{
obj.status = false;
obj.message = "获取信息失败:" + ex.Message;
}
return Content(JsonConvert.SerializeObject(obj, Formatting.Indented));
}
/// <summary>
/// Response返回信息类
/// </summary>
public class ResponseResult
{
/// <summary>
/// 状态
/// </summary>
public bool status;
/// <summary>
/// 备注信息
/// </summary>
public string message;
/// <summary>
/// 返回主体
/// </summary>
public object info;
}