Creating json using jackson and ignoring object in some condition - java

i want to apply #JsonIgnore in some condition only .
for example in one case i may only need test object not all the questions in test.
but in other case i may required to have all the question as well by using #JsonManagedReference
class Test{
private string testName;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="abc")
#JsonIgnore
private Set<question> question;
}

Try out #JsonView. It allows you to conditionally include/suppress properties based on a view (a marker class) that is provided during serialization.
class Test {
private String testName;
#JsonView(SomeCondition.class)
private Set<Question> questions;
}
#GET
#Path("/testWithCondition")
#JsonView(SomeCondition.class)
public Response getTestWithCondition() {
Test test = testService.lookupTest();
return Response.ok(test).build();
}
Note: You may have to disable MapperFeature.DEFAULT_VIEW_INCLUSION on your ObjectMapper.

Related

Javax #Valid Annotation in Inner NEsted Objects

I want to use javax validation on poco objects that contain complex types. In my code, I want to validate the PersonDetail object inside my Person class. If I don't use the #Valid PersonDetail, then validations on that subclass don't work.
Is there any way to validate nested objects without the #Valid annotation on each one?
public class Person {
#Pattern(regexp = "^[a-zA-Z]+$")
private String surname;
#Valid(//without this personDetails validations not worked)
private PersonDetail personDetail;
....
PersonDetail class
public class PersonDetail {
#Pattern(regexp = "^[a-zA-Z]+$")
private String surname2;
public String getSurname2() {
return surname2;
}
No, you need #Valid on the personDetail field in order for validation to continue to look down into that field. You can configure this in other ways (validation.xml), but ultimately you need to tell the Validator to descend into the value of the personDetail field.

#JsonIgnore only for response but not for requests

Is there a way to make #JsonIgnore annotation that it will only ignore during API or HTTP response but not ignore when doing API request.
I also understand that Jackson is used with several frameworks like Restlet, Spring, etc. so what is the generic way of doing this with the ignore annotation. The annotation class does not seem to have any parameters to set this.
Consider the code below:
public class BoxModel extends Model {
#JsonIgnore
private String entityId;
#JsonIgnore
private String secret;
}
In this example, the "secret" field should not be ignored during an API request but should not return back when doing a response, e.g. a JSON response. setting this field to null does not make the field go away, it just sets the value to null and so the field is still on the response payload.
Actually, the standard way is to have 2 separate classes for request and response, so you won't have any problem at all.
If you really need to use the same class for both cases, you can put #JsonInclude(Include.NON_NULL) onto the field instead of #JsonIgnore and set secret = null; before returning the response (as you said in question) - nullable field will be hidden after that. But it's some kind of a trick.
You could potentially find a way to achieve this using Jackson JSON Views by hiding fields when serializing the object.
Example
public class Item {
#JsonView(Views.Public.class)
public int id;
#JsonView(Views.Public.class)
public String itemName;
#JsonView(Views.Internal.class)
public String ownerName;
}
#JsonView(Views.Public.class)
#RequestMapping("/items/{id}")
public Item getItemPublic(#PathVariable int id) {
return ItemManager.getById(id);
}

JPA / Jackson - Exclude fields when deserialize and include them when serialize

I have a JPA entity with a couple of fields (the real ones are more complex). I'm receiving some data via REST (POST operation in a Spring controller) and storing it right away in the JPA entities; I want to see if there is a possibility to exclude some field(s) when the request is sent, Jackson deserializes it, and constructs the object. But at the same time I want those fields to be included when I send back (object gets serialized) the response.
#Table("key_card")
public final class KeyCard {
private String username; // Don't want this to be sent as input,
// but want to be able to send it back
// in the response
#NotBlank
private final char[] password;
}
I'm just trying not to model it twice (for the request and response) if there is a way to solve this.
You can use JSON views: http://wiki.fasterxml.com/JacksonJsonView
Class Views {
static class AlwaysInclude { }
static class OnlyOnSerialize extends AlwaysInclude { }
}
And then on your view:
#Table("key_card")
public final class KeyCard {
#JsonView(Views.OnlyOnSerialize.class)
private String username;
#JsonView(Views.AlwaysInclude.class)
#NotBlank
private final char[] password;
}
To exclude a Java object property only from Json deserialization and to include instead its value during serialization you can use an appropriate combination of #JsonIgnore and #JsonProperty annotations.
In particular you should:
annotate with #JsonIgnore the property itself
annotate with #JsonIgnore its set method
annotate with #JsonProperty its get method
Here you can find an in-depth explanation and an example: Jackson: using #JsonIgnore and #JsonProperty annotations to exclude a property only from JSON deserialization

Json #JsonIgnore . How to ignore deeper?

So, I am making a project that has a class Save which contains List of GameField class. To save "Save" to DB(with Hibernate).
I'm using JSON and it works pretty good, but it is parsing all fields from GameField , which makes Json String about 600 characters long. Beacuse it is so long , I am getting org.hibernate.exception.DataException which says that size of String is too big.
I was trying to increase avalible space in database to properly store that big String but it didn't work.
So i have found #JsonIgnore and #JsonIgnoreProperties annotations to stop Json from parsing few fields. It worked but only for Save class not for GameField.
Is it possible to prevent Json from parsing any fields that i want?
Here is Save class:
public class Save {
private List<GameField> fields;
// getters setters , etc.
}
Game Field:
public class GameField {
#JsonIgnore
private boolean isSet;
private char fieldSign;
#JsonIgnore
private final int numberInArray;
}
Fragment of parsing code:
public String getEncodedSaveInString(Save save) throws JsonProcessingException {
mapper = new ObjectMapper();
return mapper.writeValueAsString(save);
}
Piece of User class
#Entity
public class User {
#Column(name = "Save")
private Save save;
}
Is there a solution?
Okay, so i found a solution. Only thing i needed to do was putting #JsonIgnore annotation above field setter. Placing it above field itself was not working
Working sample of code:
private Foo foo;
#JsonIgnore
public void setfoo(Foo newFoo){ this.foo = newFoo;}
That works fine :)

Want to hide some fields of an object that are being mapped to JSON by Jackson

I have a User class that I want to map to JSON using Jackson.
public class User {
private String name;
private int age;
private int securityCode;
// getters and setters
}
I map this to a JSON string using -
User user = getUserFromDatabase();
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(user);
I don't want to map the securityCode variable. Is there any way of configuring the mapper so that it ignores this field?
I know I can write custom data mappers or use the Streaming API but I would like to know if it possible to do it through configuration?
You have two options:
Jackson works on setters-getters of fields. So, you can just remove getter of field which you want to omit in JSON. ( If you don't need getter at other place.)
Or, you can use the #JsonIgnore annotation of Jackson on getter method of that field and you see there in no such key-value pair in resulted JSON.
#JsonIgnore
public int getSecurityCode(){
return securityCode;
}
Adding this here because somebody else may search this again in future, like me. This Answer is an extension to the Accepted Answer
You have two options:
1. Jackson works on setters-getters of fields. So, you can just remove getter of field which you want to omit in JSON. ( If you don't need getter at other place.)
2. Or, you can use the `#JsonIgnore` [annotation of Jackson][1] on getter method of that field and you see there in no such key-value pair in resulted JSON.
#JsonIgnore
public int getSecurityCode(){
return securityCode;
}
Actually, newer version of Jackson added READ_ONLY and WRITE_ONLY annotation arguments for JsonProperty. So you could also do something like this.
#JsonProperty(access = Access.WRITE_ONLY)
private String securityCode;
instead of
#JsonIgnore
public int getSecurityCode(){
return securityCode;
}
you also can gather all properties on an annotation class
#JsonIgnoreProperties( { "applications" })
public MyClass ...
String applications;
If you don't want to put annotations on your Pojos you can also use Genson.
Here is how you can exclude a field with it without any annotations (you can also use annotations if you want, but you have the choice).
Genson genson = new Genson.Builder().exclude("securityCode", User.class).create();
// and then
String json = genson.serialize(user);
Field Level:
public class User {
private String name;
private int age;
#JsonIgnore
private int securityCode;
// getters and setters
}
Class Level:
#JsonIgnoreProperties(value = { "securityCode" })
public class User {
private String name;
private int age;
private int securityCode;
}
if you are using GSON you have to mark the field/member declarations as #Expose and use the GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
Don't forget to mark your sub classes with #Expose otherwise the fields won't show.
I suggest you use this.
#JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private int securityCode;
This allows you to set the value of securityCode(especially if you use lombok #Setter) and also prevent the field from showing up in the GET request.
I had a similar case where I needed some property to be deserialized (JSON to Object) but not serialized (Object to JSON)
First i went for #JsonIgnore - it did prevent serialization of unwanted property, but failed to de-serialize it too. Trying value attribute didn't help either as it requires some condition.
Finally, working #JsonProperty with access attribute worked like a charm.

Categories

Resources