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.
getPlayer()
, which is returning a player: name, id, age, position.
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
The Jackson @JsonIgnore annotation can be used to ignore a certain property or field of a Java object. The property can be ignored both when reading JSON into Java objects and when writing Java objects into JSON.
To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.
You can ignore null fields at the class level by using @JsonInclude(Include. NON_NULL) to only include non-null fields, thus excluding any attribute whose value is null. You can also use the same annotation at the field level to instruct Jackson to ignore that field while converting Java object to json if it's null.
The Jackson @JsonIgnoreType annotation can be used to ignore a class during the serialization process and it can mark all the properties or fields of a class to be ignored while serializing and deserializing a JSON object.
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"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With