当前位置: 首页 > 知识库问答 >
问题:

使用@JsonView的Spring Json-序列化返回关联的空对象

党航
2023-03-14

我有一个带有JPA和JSON序列化的Spring Boot项目。我尝试使用@JsonView只序列化指定的属性。它工作正常,但对于我在Order中的关联(例如Order.user),它序列化了空的Json对象。

我使用以下依赖项

  • Spring护套2.0.1。释放

请参阅以下Json-Result:

{
  "content" : {
    "orderResources" : [ {
      "receiptDate" : "2019-08-14",
      "state" : "BILL_CREATED",
      "user" : { },
      "employer" : { },
      "orderplace" : { },
      "propertyManagement" : null,
      "plannings" : [ { } ]
    }, {
      "receiptDate" : "2019-08-17",
      "state" : "BILL_CREATED",
      "user" : { },
      "employer" : { },
      "orderplace" : { },
      "propertyManagement" : null,
      "plannings" : [ ]
    } ]
  },
  "links" : {
    "next" : {
      "href" : "https://orderbook-demo.localhost:8443/api/order?page=1"
    },
    "1" : {
      "href" : "https://orderbook-demo.localhost:8443/api/order?page=1"
    }
  },
  "page" : {
    "size" : 6,
    "totalElements" : 2,
    "totalPages" : 1,
    "number" : 0
  }
}

我的实体

订单

@Entity
@JsonRootName("Order")
@BatchSize(size = 100 )
@Table(name="`order`")
@Access(AccessType.FIELD)
public class Order extends BaseEntity {

    private static final long serialVersionUID = 1L;

    @Column(name="receipt_date", nullable = false)
    @Type(type = "de.orderbook.hibernate.type.LocalDateUserType")
    @JsonSerialize(using = LocalDateJsonSerializer.class)
    @JsonDeserialize(using = LocalDateJsonDeserializer.class)
    @JsonProperty
    @JsonView(View.ListView.class)
    private LocalDate receiptDate;

    @Column(name="state", nullable = false)
    @Enumerated(value = EnumType.STRING)
    @JsonProperty
    @JsonView(View.ListView.class)
    private State state = State.OPEN;

    @ManyToOne
    @JoinColumn(name = "offer_id")
    @JsonProperty
    @JsonIgnore
    private Offer offer;

    @OneToMany(targetEntity = OrderOrderdetail.class, mappedBy = "order", orphanRemoval = true, cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @PrimaryKeyJoinColumn
    @BatchSize(size = 100)
    @JsonProperty
    private List<OrderOrderdetail> orderdetails = new ArrayList<>(10);

    @ManyToOne(targetEntity = Address.class, cascade = CascadeType.ALL)
    @JoinColumn(name= "employer_id")
    @Fetch(FetchMode.SELECT)
    @BatchSize(size = 100)
    @JsonProperty
    @JsonView(View.ListView.class)
    private Address employer;

    @ManyToOne(targetEntity = Address.class, cascade = CascadeType.ALL)
    @JoinColumn(name= "orderplace_id")
    @Fetch(FetchMode.SELECT)
    @BatchSize(size = 100)
    @JsonProperty
    @JsonView(View.ListView.class)
    private Address orderplace;

    @ManyToOne(targetEntity = Address.class, cascade = CascadeType.ALL)
    @JoinColumn(name= "property_management_id")
    @Fetch(FetchMode.SELECT)
    @BatchSize(size = 100)
    @JsonProperty
    @JsonView(View.ListView.class)
    private Address propertyManagement;

    @ManyToOne
    @JoinColumn(name="user_id")
    @BatchSize(size = 100 )
    @JsonProperty
    @JsonView(View.ListView.class)
    private User user;

    @OneToMany(targetEntity = Planning.class, mappedBy = "order", cascade = CascadeType.ALL)
    @BatchSize(size = 100 )
    @JsonProperty
    @JsonView(View.ListView.class)
    private List<Planning> plannings = new ArrayList<Planning>(3);

    public Order() {
        super();
    }

    public Order(Offer offer) {
        super();
        this.receiptDate = LocalDate.now();
        this.employer = offer.getEmployer();
        this.orderplace = offer.getOrderplace();
        this.propertyManagement = offer.getPropertyManagement();
        this.user = offer.getUser();
        this.offer = offer;
        for (OfferOrderdetail orderdetail : offer.getOrderdetails()) {
            OrderOrderdetail orderOrderdetail = new OrderOrderdetail(orderdetail.getOrderdetail(), orderdetail.getCount());
            orderOrderdetail.setOrder(this);
            this.getOrderdetails().add(orderOrderdetail);
        }
    }

    @JsonCreator
    public Order(@JsonProperty("receiptDate") LocalDate receiptDate,
                 @JsonProperty("state") State state,
                 @JsonProperty("user") User user,
                 @JsonProperty("employer") Address employer,
                 @JsonProperty("orderplace") Address orderplace,
                 @JsonProperty("propertyManagement") Address propertyManagement,
                 @JsonProperty("orderdetails") List<OrderOrderdetail> orderdetails,
                 @JsonProperty("plannings") List<Planning> plannings
    ) {
        super();
        this.receiptDate = receiptDate;
        this.state = state;
        this.user = user;
        this.employer = employer;
        this.orderplace = orderplace;
        this.propertyManagement = propertyManagement;
        this.orderdetails = orderdetails;
        this.plannings = plannings;
    }

    public LocalDate getReceiptDate() {
        return receiptDate;
    }

    public void setReceiptDate(LocalDate receiptDate) {
        this.receiptDate = receiptDate;
    }

    public List<OrderOrderdetail> getOrderdetails() {
        return orderdetails;
    }

    public void setOrderdetails(List<OrderOrderdetail> orderdetails) {
        this.orderdetails = orderdetails;
    }

    public void addOrderdetail(OrderOrderdetail orderdetail) {
        this.orderdetails.add(orderdetail);
    }

    public void removeOrderdetail(OrderOrderdetail orderdetail) {
        this.orderdetails.remove(orderdetail);
    }

    public boolean containsOrderdetail(OrderOrderdetail orderdetail) {
        return this.orderdetails.contains(orderdetail);
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public List<Planning> getPlannings() {
        return plannings;
    }

    public void addPlanning(Planning planning) {
        this.plannings.add(planning);
    }

    public void removePlanning(Planning planning) {
        this.plannings.remove(planning);
    }

    public State getState() {
        return state;
    }

    public void setState(State state) {
        this.state = state;
    }

    public Address getEmployer() {
        return employer;
    }

    public void setEmployer(Address employer) {
        this.employer = employer;
    }

    public Address getOrderplace() {
        return orderplace;
    }

    public void setOrderplace(Address orderplace) {
        this.orderplace = orderplace;
    }

    public Address getPropertyManagement() {
        return propertyManagement;
    }

    public void setPropertyManagement(Address propertyManagement) {
        this.propertyManagement = propertyManagement;
    }

    public void setPlannings(List<Planning> plannings) {
        this.plannings = plannings;
    }

    public Offer getOffer() {
        return offer;
    }

    public void setOffer(Offer offer) {
        this.offer = offer;
    }
}

用户

@Entity
@Table(name="`user`")
@JsonView(View.ListView.class)
public class User extends BaseEntity {

    private static final long serialVersionUID = 1L;

    @JsonProperty
    @JsonView(View.ListView.class)
    private String name;

    @NaturalId
    @JsonProperty
    @JsonView(View.ListView.class)
    private String username;

    @JsonProperty
    @JsonView(View.ListView.class)
    private String email;

    private @JsonIgnore String password;

    @JsonProperty
    @JsonView(View.ListView.class)
    private boolean enabled;

    @OneToMany(targetEntity = Authority.class)
    @JoinColumn(name = "username", referencedColumnName = "username")
    @BatchSize(size = 100)
    @JsonProperty
    @JsonView(View.ListView.class)
    private List<Authority> roles;

    public User() {
        super();
    }

    public User(String username, String name, String password, String email, boolean enabled, Authority... roles) {
        super();
        this.username = username;
        this.name = name;
        this.email = email;
        this.enabled = enabled;
        this.setPassword(password);
        this.roles = roles == null ? Collections.emptyList() : Arrays.asList(roles);
    }

    @JsonCreator
    public User(@JsonProperty("username") String username, @JsonProperty("name") String name, @JsonProperty("email") String email, @JsonProperty("enabled") boolean enabled, @JsonProperty("roles") List<Authority> roles) {
        super();
        this.username = username;
        this.name = name;
        this.email = email;
        this.enabled = enabled;
        this.roles = roles == null ? Collections.emptyList() : roles;
    }

    public User(String username) {
        super();
        this.username = username;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public List<Authority> getRoles() {
        return roles;
    }

    public void setRoles(List<Authority> roles) {
        this.roles = roles;
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }
}

我的控制器

@Controller
public class OrderController extends BaseController<Order, OrderRepository> {

    private static int PAGE_SIZE = 6;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private BillRepository billRepository;

    @Transactional
    @JsonView(View.ListView.class)
    @RequestMapping(value = "/api/order", method = RequestMethod.GET, headers = "content-type=application/json", consumes = "*/*", produces = "application/json")
    public @ResponseBody
    HttpEntity<OrderPagedResource> findAll(Principal principal, @RequestParam(name="page") Long page) {
        List<Order> list = super.list(page, Long.valueOf(PAGE_SIZE));

        for (Order order : list) {
            Hibernate.initialize(order.getPlannings());
            Hibernate.initialize(order.getUser().getRoles());
        }
        List<OrderResource> resources = new OrderResourceAssembler().toResources(list);
        Long count = this.repository.count();
        return new HttpEntity<OrderPagedResource>(new OrderPagedResource(resources, new MyPagedMetadata(PAGE_SIZE, page, count)));
    }
}

订单资源

public class OrderResource extends ResourceSupport {
    @JsonUnwrapped
    @JsonView(View.ListView.class)
    private Order content;

    public OrderResource(Order order) {
        super();
        this.content = order;
    }

    public Order getContent() {
        return content;
    }

    public void setContent(Order content) {
        this.content = content;
    }
}

订单页面资源

public class OrderPagedResource extends PagedResources<OrderResource> {
    private Map<String, MyLink> links = new HashMap(5);

    public OrderPagedResource(Collection<OrderResource> content, PageMetadata metadata) {
        super(content, metadata);
        for (int i = 1; i <= metadata.getTotalPages(); i++) {
            if (i == metadata.getNumber() - 1)
                this.links.put("prev", new MyLink(linkTo(OrderController.class).slash("/api/order?page=" + i).withRel("prev")));
            if (i == metadata.getNumber() + 1)
                this.links.put("next", new MyLink(linkTo(OrderController.class).slash("/api/order?page=" + i).withRel("next")));
            this.links.put(Integer.toString(i), new MyLink(linkTo(OrderController.class).slash("/api/order?page=" + i).withRel(Integer.toString(i))));
        }
    }

    @Override
    @JsonProperty("page")
    @JsonView(View.ListView.class)
    public PageMetadata getMetadata() {
        return super.getMetadata();
    }

    @Override
    @JsonProperty("content")
    @JsonView(View.ListView.class)
    public Collection<OrderResource> getContent() {
        return super.getContent();
    }

    @JsonProperty("links")
    @JsonView(View.ListView.class)
    public Map<String, MyLink> getLinks2() {
        return this.links;
    }

    public class MyLink extends Link {
        private @XmlAttribute @JsonProperty @JsonView(View.ListView.class) String rel;
        private @XmlAttribute @JsonProperty @JsonView(View.ListView.class) String href;

        public MyLink(Link link) {
            super(link.getHref(), link.getRel());
            this.rel = link.getRel();
            this.href = link.getHref();
        }
        public MyLink(String href) {
            super(href);
            this.href = href;
        }

        public MyLink(String href, String rel) {
            super(href, rel);
            this.href = href;
            this.rel = rel;
        }

        public MyLink() {
        }

        @Override
        @JsonView(View.ListView.class)
        public String getRel() {
            return this.rel;
        }

        @Override
        @JsonView(View.ListView.class)
        public String getHref() {
            return this.href;
        }
    }
}

OrderResourceAssembler

@Component
public class OrderResourceAssembler extends ResourceAssemblerSupport<Order, OrderResource> {

    public OrderResourceAssembler() {
        super(OrderController.class, OrderResource.class);
    }

    @Transactional
    @Override
    public OrderResource toResource(Order entity) {
        OrderResource resource = new OrderResource(entity);

        resource.add(linkTo(OrderController.class).slash("/api/order/" + entity.getId()).withSelfRel());
        if (entity.getOffer() != null)
            resource.add(linkTo(OrderController.class).slash("/api/offer/" + entity.getOffer().getId()).withRel("offer"));
        resource.add(linkTo(UserController.class).slash("/api/user/" + entity.getUser().getId()).withRel("user"));

        return resource;
    }

}

共有1个答案

晏晨朗
2023-03-14

默认情况下,Spring不将子对象中的属性包含到@JsonView中。您可以将@JsonView添加到子POJO,或者通过应用以下配置启用所有子属性。

spring.jackson.mapper.default-view-inclusion=true
 类似资料:
  • 我正在学习Spring框架,我的第一个目标是使用内置序列化程序返回版本对象。 我的根类(我称之为内核),希望使用一个类来配置应用程序 控制器 我正在尝试尽可能简单,我的项目中没有任何XML文件,因为我想完全注释 我从来没有真正喜欢Spring框架中的XML驱动概念,因为大多数时候这些XML文件的内容看起来像是暴露的程序员垃圾,除了所有者之外,没有人知道如何设置。当部署工作人员不知道这是什么时,公开

  • 我正在做一个小组项目,我们遇到了一个软件序列化部分的问题。我们有类协议: 我们还有SearchResult类: 当我们通过客户端-服务器套接字连接编写协议类时,就会出现问题。问题是Protocol类中的TableModel对象在序列化/反序列化过程中的某个时刻变为null,而我们所做的任何事情都还没有解决这个问题。 到目前为止,我们已尝试: -在SearchResult中实现Serializabl

  • 假设我有这样一个Java类: 然后我有了文件如下: 然后是这样的文件: 问题是功能文件中的dob字段看起来像以下结构: 但是我希望它使用DateFormatter,这样输出就 有没有一种方法可以在不创建另一个DTO和自己进行LocalDate格式化的情况下使用空手道做到这一点?

  • 我正在使用java spark API编写一些测试应用程序。我使用的是一个不扩展可序列化接口的类。因此,为了使应用程序正常工作,我使用kryo序列化器序列化类。但我在调试时观察到的问题是,在反序列化过程中,返回的类对象变为null,并反过来抛出一个null指针异常。这似乎是关闭的问题,事情是错误的,但不确定。因为我是新的这种系列化,我不知道从哪里开始挖掘。 下面是我正在测试的代码: 下面是我正在序

  • 问题内容: 给定以下类层次结构,我希望根据类层次结构中使用的上下文,对Foo进行不同的序列化。 我希望序列化FooContainer时biz属性不显示在fooB中。因此,输出将类似于以下内容。 我本打算使用JsonView,但是必须将其应用于类的所有实例的映射器层,并且这取决于上下文。 在Jackson用户的邮件列表中,Tatu提供了最简单的解决方案(在2.0中可用),我现在可能最终会使用它。将奖

  • 我有一个简单的类来提供计数和db光标信息。 此类不需要反序列化。 多谢了。