【问题标题】:How to convert a List to Json in c# EF core web api如何在 C# EF 核心 web api 中将列表转换为 Json
【发布时间】:2020-05-05 05:41:51
【问题描述】:

我无法转换为返回 json 而不是列表。我尝试使用 Newtonsoft.Json,但没有任何效果。要么报错,要么返回null。

[HttpGet]
        public IActionResult GetUsers()
        {
            using (var context = new ProjectContext())
            {

                var MyEntity = context.User.ToList();

                return MyEntity; 
            }
        }

用户模型

using System;
using System.Collections.Generic;

namespace Project.Models
{
    public partial class User
    {
        public User()
        {
            Order= new HashSet<Order>();
        }

        public int IdUser { get; set; }
        public string Name{ get; set; }
        public string Tel{ get; set; }
        public float? Stars{ get; set; }

        public virtual SellerSeller { get; set; }
        public virtual ICollection<Order> Order{ get; set; }
    }
}

MyEntity 返回的类型是 System.Collections.Generic.List

【问题讨论】:

  • 你能告诉我们返回 JSON,MyEntity 的类型及其模型
  • 先确保MyEntity 不为空,然后使用return Json(new {date = MyEntity , Status = "success"})
  • context.User 是否返回了一些东西? MyEntity 的价值是什么
  • 当你使用 newtonsoft 时,列出的对象是否在其属性上具有序列化属性? [JsonProperty]
  • @JamesLoForti 我用var json = jsonSerialiser.Serialize (aList) ; 做到了。由于返回了错误的方法,我给出了一个错误。菜鸟错误。

标签: c# json list entity-framework entity-framework-core


【解决方案1】:

试试这个。

[HttpGet]
    public IActionResult GetUsers()
    {
        using (var context = new ProjectContext())
        {

            var MyEntity = context.User.ToList();

            return Ok(MyEntity); 
        }
    }

【讨论】:

    【解决方案2】:

    使用以下内容作为Json返回

    return Json(new { data = MyEntity,  Status = "Success" }, JsonRequestBehavior.AllowGet);
    

    【讨论】:

    • 我收到此错误“无法将类型'System.Web.Mvc.JsonResult'隐式转换为'System.Collections.Generic.IEnumerable'。存在显式转换(你错过了演员表吗?)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 2019-11-24
    • 2015-12-15
    • 2011-10-20
    • 1970-01-01
    相关资源
    最近更新 更多