向Spring JSON视图响应添加动态字段 [英] Add dynamic fields to Spring JSON view response

查看:186
本文介绍了向Spring JSON视图响应添加动态字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一种Spring方法可以通过

There is a Spring approach to filter out fields from a service response with JSON views, but i am missing an equivalent approach to enrich a response with some dynamic/syntetic fields like this;

class User{
    getFirstName(){...}
    getLastName(){...}
    getCreateDate(){...}
}

class UserViewA{
    getFullName(){
      return getLastName()+", "+getFirstName()
    }
    getCreateDate(){...}
}

class UserViewB{
    getFullName(){
      return getFirstName()+" "+getLastName()
    }
    getCreateDate(){...}
}

我可以将用户包装在视图中,但是我不想手动传播所有需要的用户字段.

I could wrap the user within the view, but I do not want to propagate all needed user fields manually.

我的另一个想法是使用用户对象扩展视图,并创建某种引用链接器,以将值引用从用户对象复制到视图,但是这会使集合变得复杂.

My other idea was to extend the views with the user object and create some sort of an reference linker to copy values references from the user object to the view, but this will get complicated with collections.

是否有其他方法或框架可以实现这一目标?根本不解决这个概念吗?

Is there some other approach or framework to achieve this? Is this concept not addressed in any way at all?

更新:

Update:

示例澄清:

  • 我不想包装User对象,因为我不想在不同的UserView对象中维护User类中的相同getter方法.
  • 我无法扩展用户,因为它是从其他资源加载的域对象.
  • 在User对象中不应引用其他UserView对象.

我正在寻找一种外观解决方案/框架/方法.

I am looking for a kind of facade solution/framework/approach.

推荐答案

使用杰克逊@JsonUnwrapped怎么样?

http://fastxml.github.io/jackson-annotations/javadoc/2.0.0/com/fasterxml/jackson/annotation/JsonUnwrapped.html

public class UserViewA {

    @JsonUnwrapped
    private User user;

    public User getUser() ...

    public String getFullName() {
        return user.getFirstName() + " " + user.getLastName()
    }
}

JsonUnwrapped只会将User的所有属性拉到根级别,并且在那里仍然拥有UserViewA的自己的属性.

JsonUnwrapped will just pull all properties of User to the root level and still have the own properties of UserViewA in there.

这篇关于向Spring JSON视图响应添加动态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆