在 ASP.net 核心中将对象转换为 Json

Convert an object to Json in ASP.net Core

我正在尝试将 "Persona" 转换并对象化为 .net Framework 4 中的 json 字符串,我需要帮助。

我试过了(使用 System.Text.Json)

public HttpResponseMessage Get(int id){
  HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    Personas persona = context.tPersonas.FirstOrDefault(p => p.idPersona == id);
    if (persona != null){
      var jsonData = JsonSerializer.Serialize(persona);
      response.Content = new StringContent(jsonData);
      response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
      return response;
    }
  else
    return response = new HttpResponseMessage(HttpStatusCode.BadRequest);            
} 

还有这个(使用 Newtonsoft.Json);

 public HttpResponseMessage Get(int id)
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            Personas persona = context.tPersonas.FirstOrDefault(p => p.idPersona == id);
            if (persona != null)
            {
                response.Content = new StringContent(JsonConvert.SerializeObject(persona));
                response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                return response;
            }
            else
                return response = new HttpResponseMessage(HttpStatusCode.BadRequest);            
        }

调试时,"persona"有数据,"Serialize"显示为空

我也试过 "Request.CreateResponse" 但由于某些奇怪的原因它不能被识别为有效代码。

我跳过了哪一步?

如果想在asp.coremvc中使用HttpResponseMessage到return的信息,需要完成以下步骤

  • 为您的安装 Microsoft.AspNetCore.Mvc.WebApiCompatShim 包 项目。
  • services.AddMvc().AddWebApiConventions(); 添加到 starup.cs 文件中的 ConfigureServices。

代码如下:

    public HttpResponseMessage Get(int id)
    {
        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
        Personas persona = _context.tPersonas.FirstOrDefault(p => p.idPersona == id);
        if (persona != null)
        {
            response.Content = new StringContent(JsonConvert.SerializeObject(persona));
            response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            return response;
        }
        else
        {
            response = new HttpResponseMessage(HttpStatusCode.BadRequest);
            response.Content = new StringContent("error message");
            return response;
        }

    } 

也可以参考.

这是邮递员的调试过程: