#JSON annotation to replace a String value with null in Java - java

I am looking for an annotation I can use to replace String value to null in Java
There are some #Json annotation that can do customization while serializing a JSON object to POJO,
I want to do something like this:
#JsonFormat(<if incoming value is SOMESTRING>, <set incoming value to null>)
String valueChangedUsingAnnotation;

Use #JsonIgnore annotation. This annotation is used when you want to ignore certain properties of a java class. It will ignore those fields annotated with when reading from json to java object and also, writing java object to json.

If incoming value is SOMETHING, set its value to null. For this you can update the setter method of that particular field in POJO class. Because, when incoming object is deserialized it invokes setter methods of each fields.
Something like below:
class Test{
//constructor, other fields and their getters and setters
private String target;
public void setTarget(String target) {
if(target.equals("abcd"){
this.target=null
}
else {
this.target=target;
}
}
}
There is no need of any JSON annotations.

Related

Why can’t Jackson deserialize single field class with RequiredArgsConstructor?

If I have a class using Lombok:
#RequiredArgsConstructor
#Getter
class Example {
private final String id;
}
And try to deserialize it from
{
“id”: “test”
}
Jackson throws an exception that although at least one creator was provided, it could not deserialize.
If I then add another final String field to that class, and add that field to the JSON, it is deserialized with no complaints.
Does anyone know what’s going on here? Why are you unable to deserialize if you only have one field?
When only way to intialize object properties is through contructor, Jackson needs to be told that deserialization should happen using constructor via #JsonCreator annotation.
Also, all the property names should be provided via #JsonProperty annotation because Jackson needs to know the sequence of attributes passed in contructor to correctly map json values to Java object attributes.
So, if you are not using lombok contructor, then constructor will look like
#JsonCreator
public Example (#JsonProperty("id") String id) {
this.id = id;
}
If you don't want to manually write the contructor, go ahead with #tashkhisi's answer.
Also, I highly doubt following could happen. Could you update the question with code showing this?
If I then add another final String field to that class, and add that field to the JSON, it is deserialized with no complaints.

Jackson json to java object mapping

If I pass a JSON like
`{
"entity":{
"name":"xyz",
"age":21
}
}`
Then , is it compulsory that my POJO should have both "name" and "age" instance variables. I mean, if I have only "name" instance field, will there be any exception while mapping?
If your JSON contains extra fields which are not present in POJO, it will throw an exception. To avoid that you can ignore additional fields using this annotation #JsonIgnoreProperties.
if field names are different, you can define at field getter using #jsonProperty. (for deserialization).
for serialization use annotation on the setter method.
#JsonIgnoreProperties(ignoreUnknown = true)
class Pojo {
private String name;
#jsonProperty("firstName")
public String getName(){
return this.name;
}
}
is it compulsory that my POJO should have both "name" and "age" instance variables
If you mean "have" as in the same names exactly, then no. You can use annotations to rename the values.
If you instead mean the class definition "contains" those values, then also it shouldn't need them. That depends on how you configure ObjectMapper, though. For example, there is an AnyGetter annotation that will allow you to collect "extra" JSON values. Therefore, it makes sense that mandatory fields are not required.

How to define optional json field using Jackson

I have an object with one optional field and can not find proper annotation to model it. Any ideas what is the proper way to do it with Jackson?
In Jackson you cannot make the difference between optional and non-optional fields. Just declare any field in your POJO. If a field is not present in your JSON structure then Jackson will not call the setter. You may keep track of wether a setter has been called with a flag in the POJO.
Coming late to the party...
Using Jackson 2.8.6 via Spring HttpMessageConverter 4.3.6, I had to change my setter parameter to the unwrapped type, like so:
class Foo {
private Optional<Bar> bar;
public void setBar(Bar bar) { // NOT Optional<Bar>, this gives me Optional.empty()
this.bar = Optional.of(bar);
}
// getter doesn't need to be changed
}

Java Jersey use GET to return JSON that returns only some fields instead of all

Does naybody knows a way to use Jersey's GET method to return a JSON that returns only some fields of an entity instead of all?
Does anybody know a way to use Jersey's GET method to return a JSON that returns only some fields of an entity instead of all?
E.g. in the following class I want to receive (with POST) values for 'name' and for 'confidential', buy while returning (with GET) I only need 'name' value, not 'confidential'.
#Entity
#Table(name = "a")
#XmlRootElement
#JsonIgnoreProperties({"confifentialInfo"})
public class A extends B implements Serializable {
private String name;
#Basic(optional = false)
private String confifentialInfo;
// more fields, getters and setters
}
If you are using the JAXB approach, you can mark fields with #XmlTransient to omit them. If you are using POJO mapping or want to exclude fields only for some requests, you should construct the JSON with the low level JSON API.
If you are using Jackson, you can use the annotation #JsonIgnore for methods
Marker annotation similar to javax.xml.bind.annotation.XmlTransient
that indicates that the annotated method is to be ignored by
introspection-based serialization and deserialization functionality.
That is, it should not be consider a "getter", "setter" or "creator".
And #JsonIgnoreProperties for properties
Annotation that can be used to either suppress serialization of
properties (during serialization), or ignore processing of JSON
properties read (during deserialization).

Rename JSON fields used by MappingJacksonJsonView in Spring

I'm using MappingJacksonJsonView to serialize to JSON a class, however, I'd like to be able to rename some of the fields from the default name based on the getter name.
This is because I've to output field names like "delete_url" and "delete_type" for jQuery file upload. I'm using #Jsonserialize annotation to hand pick the fields to serialize.
#JsonAutoDetect(getterVisibility = Visibility.NONE)
public interface Picture {
#JsonSerialize
String getName();
#JsonSerialize
String getDelete_url();
...
For instance, I'm forced to call a method getDelete_url(), while I'd like to call it getDeleteUrl(), but still output the key "delete_url" when serializing to JSON.
You should be able to qualify using #JsonProperty.
#JsonAutoDetect(getterVisibility = Visibility.NONE)
public interface Picture {
#JsonSerialize
#JsonProperty("name")
String getName();
#JsonSerialize
#JsonProperty("delete_url")
String getDeleteUrl();
//...
Have you tried using the #JsonProperty annotation?
"Defines name of the logical property, i.e. Json object field name to use for the property: if empty String (which is the default), will use name of the field that is annotated."

Categories

Resources