关于spring:spring-JsonView解决循环对象引用遇到报错

前言:

本周次要工夫用来写社区治理的后盾,遇到的次要问题就是对于初期对于模块化了解不够粗浅。导致本人一个简略的模块被一直的放大。

遇到问题:

问题形容:

根据前台MockApi来进行单元测试,其中返回后盾的返回数据包含:县、乡镇、社区、小区

县:乡镇:社区:小区 均为一对多的关系。

结构返回数据代码:

public static County getOneCounty() {
    logger.debug("结构返回数据县")
    County county = new County();
    county.setId(new Random().nextLong());
    county.setName(new RandomString().nextString());
    logger.debug("获取乡镇");
    logger.debug("乡镇中有社区List,社区中有小区List")
    Town town = TownControllerTest.getOneTown();
    county.getTowns().add(town);

    return county;
  }

测试代码

@Test
  void getCounty() throws Exception {
    String url = baseUrl + "/county";

    County county = getOneCounty();

    Mockito.doReturn(county).when(this.systemService).getCounty();

    this.mockMvc.perform(MockMvcRequestBuilders.get(url))
        .andExpect(MockMvcResultMatchers.jsonPath("$.id").value(county.getId()))
        .andExpect(MockMvcResultMatchers.jsonPath("$.name").value(county.getName()))
        .andExpect(MockMvcResultMatchers.jsonPath("$.towns[0].id").exists())
        .andExpect(MockMvcResultMatchers.jsonPath("$.towns[0].communities[0].id").exists())
        .andExpect(MockMvcResultMatchers.jsonPath("$.towns[0].communities[0].villages[0].id").exists())
        .andExpect(MockMvcResultMatchers.status().isOk());
  }

报错

through reference chain: club.yunzhi.smartcommunity.entity.Community["town"]->club.yunzhi.smartcommunity.entity.Town["communities"]->java.util.ArrayList[0]->club.yunzhi.smartcommunity.entity.Community["town"]->club.yunzhi.smartcommunity.entity.Town["communities"]->java.util.ArrayList[0]->club.yunzhi.smartcommunity.entity.Community["town"]->club.yunzhi.smartcommunity.entity.Town["communities"]->java.util.ArrayList[0]->club.yunzhi.smartcommunity.entity.Community["town"]->club.yunzhi.smartcommunity.entity.Town["communities"]......

解决:

看谬误提醒

依据报错提醒能够看出是始终在town和community循环了:town中蕴含community,每个community又蕴含一个town,如此一直的获取。

查看返回数据

论断:猜测是我在town的community中设置了town吗?

管他呢,删了试试

再报错:

community.village[0]不存在!

打断点测试


明明有village[0]啊

忽然想到JsonView

查看C层代码:

public class GetAllCountyJsonView implements 
      County.TownJsonView, 
      Town.CommunityJsonView, 
      Community.TownJsonView {
    
 }

豁然开朗:County->town->community->town->community->town…..

总结:

感激单元测试,因为有了单元测试才可能在只有后盾的状况下排查出本人后盾的BUG,同时也对于JsonView加深了了解

版权申明

本文作者:河北工业大学梦云智开发团队 – 郝泽龙

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理