热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

JSON响应不包括所有项。-JSONresponsedoesnotincludeallitems

ForsomereasononlythefirstitemofeacharrayisbeingreturnedasJSON,anyclueswhy?由于某种原因,每

For some reason only the first item of each array is being returned as JSON, any clues why?

由于某种原因,每个数组的第一个条目被返回为JSON,有什么线索吗?

Here is what I see during debugging, as you can tell, I have two items in 'Category' and two items in 'Tasks':

下面是我在调试过程中看到的,正如您所看到的,我在“Category”中有两个条目,在“Tasks”中有两个条目:

enter image description here

Postman JSON result (it should return all items, shouldn't it?): enter image description here

Postman JSON结果(它应该返回所有项,不是吗?)

For reference, here is my 'Category.cs':

以下是我的“类别。c”:

public class Category
{
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public DateTime Timestamp { get; set; }
    public string Username { get; set; }

    public ApplicationUser ApplicationUser { get; set; }

    public virtual ICollection Tasks { get; set; }
}

My 'Task.cs':

我的“Task.cs”:

public class Task
{
    public int TaskId { get; set; }
    public string Name { get; set; }
    public DateTime Timestamp { get; set; }

    public virtual Category Category { get; set; }
}

and my Api:

和我的Api:

    [HttpGet]
    public JsonResult Get()
    {
        var result = _repo.GetAllForUser("lucas@test.com");

        return Json(result);
    }

And repository:

和存储库:

    public IEnumerable GetAllForUser(string name)
    {
        return _ctx.Categories
                    .Where(c => c.ApplicationUser.UserName == name)
                    .Include(c => c.Tasks)
                    .ToList();           
    }

Here is what I insert into database, and what I should retrieve from the Api:

以下是我插入到数据库中的内容,以及我应该从Api中获取的内容:

        categories.Add(new Category
        {
            Name = "cat 1",
            Tasks = new List
            {
                new Task { Name="task 1" },
                new Task { Name="task 2" }
            }
        });
        categories.Add(new Category
        {
            Name = "cat 2",
            Tasks = new List
            {
                new Task { Name="task 3" },
                new Task { Name="task 4" }
            }
        });

2 个解决方案

#1


1  

As Kiran pointed out, you have circular references in your models, which is causing an exception. This bug is incorrectly making it look like the request is completing with partial data. (The circular reference is Category -> Tasks -> Task -> Category)

正如Kiran所指出的,您的模型中有循环引用,这会导致异常。这个错误使它看起来像请求用部分数据完成。(循环引用为Category -> Tasks -> Task -> Category)

What's actually happening is an unhandled exception halfway through the JSON serialization of the response. Instead of aborting the connection (as it should), ASP.NET Core is sending back everything that was serialized until the error occurred.

实际上,在响应的JSON序列化过程中出现了一个未处理的异常。而不是像应该的那样中止连接,而是ASP。NET Core将发送被序列化的所有内容,直到发生错误。

You can either define a DTO class that doesn't include the reference from Task back to Category, or return an anonymous type:

您可以定义一个不包含从任务返回到类别的引用的DTO类,或者返回一个匿名类型:

[HttpGet]
public JsonResult Get()
{
    var result = _repo.GetAllForUser("lucas@test.com");

    var respOnse= new {
        categoryId: result.CategoryId,
        name: result.Name,
        timestamp: result.Timestamp,
        username: result.Username,
        tasks: result.Tasks.Select(t => new {
            taskId: t.TaskId,
            name: t.Name,
            timestamp: t.Timestamp
        })
    };

    return Json(response);
}

If you do this often, it makes sense to create DTO class and use a tool like AutoMapper to do the mapping for you.

如果您经常这样做,那么创建DTO类并使用AutoMapper之类的工具为您完成映射是有意义的。

#2


0  

Nate's answer is perfect, he responded with great recommendations that pointed me to find great solution for my scenario. I have decided to share it in case someone would run into similar problem. As a reminder, this is ASP.NET Core Model First MVC project with Api. I have utilized AutoMapper for mapping my Model First classes with corresponding view models.

内特的回答是完美的,他的回答非常棒,他建议我为我的设想找到一个很好的解决方案。我决定分享它,以防有人遇到类似的问题。作为提醒,这是ASP。NET核心模型第一个使用Api的MVC项目。我使用AutoMapper将我的模型第一个类与相应的视图模型映射。

Here are my Model First classes:

这是我的模型第一课:

public class Category
{
    public Category()
    {
        Tasks = new HashSet();
    }

    public int CategoryId { get; set; }
    public string Name { get; set; }
    public DateTime Timestamp { get; set; }
    public string Username { get; set; }

    public ApplicationUser ApplicationUser { get; set; }

    public virtual ICollection Tasks { get; set; }
}

public class Task
{
    public int TaskId { get; set; }
    public string Name { get; set; }
    public DateTime Timestamp { get; set; }
    public int CategoryId { get; set; }

    public virtual Category Category { get; set; }
}

Corresponding view models:

相应的视图模型:

public class CategoryViewModel
{
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public DateTime Timestamp { get; set; }

    public IEnumerable Tasks { get; set; }
}

public class TaskViewModel
{
    public int TaskId { get; set; }
    public string Name { get; set; }
    public DateTime Timestamp { get; set; }
}

AutoMapper setup in 'Setup.cs' file:

AutoMapper设置”设置。cs的文件:

Mapper.Initialize(cOnfig=>
        {
            config.CreateMap().ReverseMap();
            config.CreateMap().ReverseMap();
        });

And finally my fully working Api method:

最后,我的全工作Api方法:

[HttpGet]
    public JsonResult Get()
    {
        var result = Mapper.Map>(_repo.GetAllForUser("lucas@test.com"));

        return Json(result);
    }

推荐阅读
  • 本文讨论了在使用Git进行版本控制时,如何提供类似CVS中自动增加版本号的功能。作者介绍了Git中的其他版本表示方式,如git describe命令,并提供了使用这些表示方式来确定文件更新情况的示例。此外,文章还介绍了启用$Id:$功能的方法,并讨论了一些开发者在使用Git时的需求和使用场景。 ... [详细]
  • Summarize function is doing alignment without timezone ?
    Hi.Imtryingtogetsummarizefrom00:00otfirstdayofthismonthametric, ... [详细]
  • linux时间字符串转正常时间 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • Echarts图表重复加载、axis重复多次请求问题解决记录
    文章目录1.需求描述2.问题描述正常状态:问题状态:3.解决方法1.需求描述使用Echats实现了一个中国地图:通过选择查询周期&#x ... [详细]
  • 本文介绍了设计师伊振华受邀参与沈阳市智慧城市运行管理中心项目的整体设计,并以数字赋能和创新驱动高质量发展的理念,建设了集成、智慧、高效的一体化城市综合管理平台,促进了城市的数字化转型。该中心被称为当代城市的智能心脏,为沈阳市的智慧城市建设做出了重要贡献。 ... [详细]
  • http:my.oschina.netleejun2005blog136820刚看到群里又有同学在说HTTP协议下的Get请求参数长度是有大小限制的,最大不能超过XX ... [详细]
  • 计算机存储系统的层次结构及其优势
    本文介绍了计算机存储系统的层次结构,包括高速缓存、主存储器和辅助存储器三个层次。通过分层存储数据可以提高程序的执行效率。计算机存储系统的层次结构将各种不同存储容量、存取速度和价格的存储器有机组合成整体,形成可寻址存储空间比主存储器空间大得多的存储整体。由于辅助存储器容量大、价格低,使得整体存储系统的平均价格降低。同时,高速缓存的存取速度可以和CPU的工作速度相匹配,进一步提高程序执行效率。 ... [详细]
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
  • 自动轮播,反转播放的ViewPagerAdapter的使用方法和效果展示
    本文介绍了如何使用自动轮播、反转播放的ViewPagerAdapter,并展示了其效果。该ViewPagerAdapter支持无限循环、触摸暂停、切换缩放等功能。同时提供了使用GIF.gif的示例和github地址。通过LoopFragmentPagerAdapter类的getActualCount、getActualItem和getActualPagerTitle方法可以实现自定义的循环效果和标题展示。 ... [详细]
  • SpringMVC接收请求参数的方式总结
    本文总结了在SpringMVC开发中处理控制器参数的各种方式,包括处理使用@RequestParam注解的参数、MultipartFile类型参数和Simple类型参数的RequestParamMethodArgumentResolver,处理@RequestBody注解的参数的RequestResponseBodyMethodProcessor,以及PathVariableMapMethodArgumentResol等子类。 ... [详细]
  • 本文介绍了如何使用JSONObiect和Gson相关方法实现json数据与kotlin对象的相互转换。首先解释了JSON的概念和数据格式,然后详细介绍了相关API,包括JSONObject和Gson的使用方法。接着讲解了如何将json格式的字符串转换为kotlin对象或List,以及如何将kotlin对象转换为json字符串。最后提到了使用Map封装json对象的特殊情况。文章还对JSON和XML进行了比较,指出了JSON的优势和缺点。 ... [详细]
  • 本文介绍了一个React Native新手在尝试将数据发布到服务器时遇到的问题,以及他的React Native代码和服务器端代码。他使用fetch方法将数据发送到服务器,但无法在服务器端读取/获取发布的数据。 ... [详细]
  • SpringBoot整合SpringSecurity+JWT实现单点登录
    SpringBoot整合SpringSecurity+JWT实现单点登录,Go语言社区,Golang程序员人脉社 ... [详细]
author-avatar
廊坊0316慢摇酒吧_196
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有