简体   繁体   中英

How to add and ignore a field for json response

I'm using RestEasy and hibernate to return response in Jackson. I have a bean Player having fields: name, id, age, position.

Now, I'm implementing two GET rest methods for returing json.

  1. getPlayer() , which is returning a player: name, id, age, position.

  2. getPlayers() , which is returning a list of players, but with this list of players, i do not want to return position.

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.

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.

You can read more about it here: 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):

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM