[英]How to add and ignore a field for json response
I'm using RestEasy and hibernate to return response in Jackson. 我正在使用RestEasy和hibernate在Jackson中返回响应。 I have a bean Player having fields: name, id, age, position.
我有一个bean播放器,其中包含字段:name,id,age,position。
Now, I'm implementing two GET
rest methods for returing json. 现在,我正在实现两个
GET
rest方法来恢复json。
getPlayer()
, which is returning a player: name, id, age, position. getPlayer()
,它返回一个玩家:名字,身份,年龄,位置。
getPlayers()
, which is returning a list of players, but with this list of players, i do not want to return position. getPlayers()
,它返回一个玩家列表,但有了这个玩家列表,我不想返回位置。
I mean, how can I add a field for one response and ignore it for another response. 我的意思是,我如何为一个响应添加一个字段而忽略它以获得另一个响应。
Please suggest. 请建议。
Thanks 谢谢
You should use @JsonIgnore
annotation on the POJO getter. 您应该在POJO getter上使用
@JsonIgnore
注释。
http://jackson.codehaus.org/1.0.1/javadoc/org/codehaus/jackson/annotate/JsonIgnore.html http://jackson.codehaus.org/1.0.1/javadoc/org/codehaus/jackson/annotate/JsonIgnore.html
Update: 更新:
You need to use interface with @JsonIgnoreProperties
and set it as @JSONFilter
on your Request mapping. 您需要使用
@JsonIgnoreProperties
接口,并在Request映射@JsonIgnoreProperties
其设置为@JSONFilter
。
You can read more about it here: http://www.jroller.com/RickHigh/entry/filtering_json_feeds_from_spring 您可以在此处阅读更多相关信息: http : //www.jroller.com/RickHigh/entry/filtering_json_feeds_from_spring
I am using tomee, to ignore a field in json response transient
works for me, but i don't know if it is the correct way to go (there is no jackson visible to my application, i just included jee-web api): 我正在使用tomee,忽略json响应
transient
一个字段为我工作,但我不知道它是否是正确的方法(我的应用程序没有杰克逊可见,我只包括jee-web api):
Servlet Servlet的
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/")
@Produces({ MediaType.APPLICATION_JSON })
public class JsonApi {
@GET
@Path("testapi")
public MyObject testApi() {
return new MyObject("myname", "mycolor");
}
}
Object 宾语
public class MyObject {
public MyObject() {
}
public MyObject(String name, String color) {
this.name = name;
this.color = color;
}
public String name;
public transient String color;
}
Response 响应
{"name":"myname"}
Can't you simply null out the position field? 你不能简单地取消位置字段吗?
@GET
@Path("/players")
public List<Player> getPlayers(){
List<Player> players = getPlayersFromHibernate();
for(Player player : players)
player.setPosition(null);
return players;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.