[BAEL-19673] - Move articles out of jackson part 1

This commit is contained in:
catalin-burcea
2019-11-22 14:52:42 +02:00
parent dd9a7593c1
commit 6eb57f91eb
97 changed files with 894 additions and 210 deletions
+11
View File
@@ -0,0 +1,11 @@
## Jackson Annotations
This module contains articles about Jackson annotations.
### Relevant Articles:
- [Guide to @JsonFormat in Jackson](https://www.baeldung.com/jackson-jsonformat)
- [More Jackson Annotations](https://www.baeldung.com/jackson-advanced-annotations)
- [Jackson Annotation Examples](https://www.baeldung.com/jackson-annotations)
- [Jackson Bidirectional Relationships](https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion)
- [Jackson Change Name of Field](https://www.baeldung.com/jackson-name-of-property)
- [Jackson Ignore Properties on Marshalling](https://www.baeldung.com/jackson-ignore-properties-on-serialization)
+60
View File
@@ -0,0 +1,60 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>jackson-annotations</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jackson-annotations</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jsonSchema</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-path</artifactId>
<version>${rest-assured.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>jackson-annotations</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<assertj.version>3.11.0</assertj.version>
<rest-assured.version>3.1.1</rest-assured.version>
</properties>
</project>
@@ -0,0 +1,31 @@
package com.baeldung.jackson.annotation;
import com.fasterxml.jackson.annotation.JsonAlias;
public class AliasBean {
@JsonAlias({ "fName", "f_name" })
private String firstName;
private String lastName;
public AliasBean() {
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
@@ -0,0 +1,15 @@
package com.baeldung.jackson.annotation;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class BeanWithCreator {
public int id;
public String name;
@JsonCreator
public BeanWithCreator(@JsonProperty("id") final int id, @JsonProperty("theName") final String name) {
this.id = id;
this.name = name;
}
}
@@ -0,0 +1,37 @@
package com.baeldung.jackson.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Date;
import com.baeldung.jackson.annotation.BeanWithCustomAnnotation.CustomAnnotation;
import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@CustomAnnotation
public class BeanWithCustomAnnotation {
public int id;
public String name;
public Date dateCreated;
public BeanWithCustomAnnotation() {
}
public BeanWithCustomAnnotation(final int id, final String name, final Date dateCreated) {
this.id = id;
this.name = name;
this.dateCreated = dateCreated;
}
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonInclude(Include.NON_NULL)
@JsonPropertyOrder({ "name", "id", "dateCreated" })
public @interface CustomAnnotation {
}
}
@@ -0,0 +1,18 @@
package com.baeldung.jackson.annotation;
import com.fasterxml.jackson.annotation.JsonFilter;
@JsonFilter("myFilter")
public class BeanWithFilter {
public int id;
public String name;
public BeanWithFilter() {
}
public BeanWithFilter(final int id, final String name) {
this.id = id;
this.name = name;
}
}
@@ -0,0 +1,31 @@
package com.baeldung.jackson.annotation;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSetter;
public class BeanWithGetter {
public int id;
private String name;
public BeanWithGetter() {
}
public BeanWithGetter(final int id, final String name) {
this.id = id;
this.name = name;
}
@JsonProperty("name")
@JsonSetter("name")
public void setTheName(final String name) {
this.name = name;
}
@JsonProperty("name")
@JsonGetter("name")
public String getTheName() {
return name;
}
}
@@ -0,0 +1,20 @@
package com.baeldung.jackson.annotation;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties({ "id" })
public class BeanWithIgnore {
@JsonIgnore
public int id;
public String name;
public BeanWithIgnore() {
}
public BeanWithIgnore(final int id, final String name) {
this.id = id;
this.name = name;
}
}
@@ -0,0 +1,18 @@
package com.baeldung.jackson.annotation;
import com.fasterxml.jackson.annotation.JacksonInject;
public class BeanWithInject {
@JacksonInject
public int id;
public String name;
public BeanWithInject() {
}
public BeanWithInject(final int id, final String name) {
this.id = id;
this.name = name;
}
}
@@ -0,0 +1,31 @@
package com.baeldung.jackson.annotation;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
public class ExtendableBean {
public String name;
private Map<String, String> properties;
public ExtendableBean() {
properties = new HashMap<String, String>();
}
public ExtendableBean(final String name) {
this.name = name;
properties = new HashMap<String, String>();
}
@JsonAnySetter
public void add(final String key, final String value) {
properties.put(key, value);
}
@JsonAnyGetter
public Map<String, String> getProperties() {
return properties;
}
}
@@ -0,0 +1,33 @@
package com.baeldung.jackson.annotation;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonSetter;
@JsonInclude(Include.NON_NULL)
@JsonPropertyOrder({ "name", "id" })
public class MyBean {
public int id;
public String name;
public MyBean() {
}
public MyBean(final int id, final String name) {
this.id = id;
this.name = name;
}
@JsonGetter("name")
public String getTheName() {
return name;
}
@JsonSetter("name")
public void setTheName(String name) {
this.name = name;
}
}
@@ -0,0 +1,19 @@
package com.baeldung.jackson.annotation;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
public class PrivateBean {
private int id;
private String name;
public PrivateBean() {
}
public PrivateBean(final int id, final String name) {
this.id = id;
this.name = name;
}
}
@@ -0,0 +1,19 @@
package com.baeldung.jackson.annotation;
import com.fasterxml.jackson.annotation.JsonRawValue;
public class RawBean {
public String name;
@JsonRawValue
public String json;
public RawBean() {
}
public RawBean(final String name, final String json) {
this.name = name;
this.json = json;
}
}
@@ -0,0 +1,34 @@
package com.baeldung.jackson.annotation;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
public class UnwrappedUser {
public int id;
@JsonUnwrapped
public Name name;
public UnwrappedUser() {
}
public UnwrappedUser(final int id, final Name name) {
this.id = id;
this.name = name;
}
public static class Name {
public String firstName;
public String lastName;
public Name() {
}
public Name(final String firstName, final String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
}
@@ -0,0 +1,34 @@
package com.baeldung.jackson.annotation;
import com.fasterxml.jackson.annotation.JsonIgnoreType;
public class UserWithIgnoreType {
public int id;
public Name name;
public UserWithIgnoreType() {
}
public UserWithIgnoreType(final int id, final Name name) {
this.id = id;
this.name = name;
}
@JsonIgnoreType
public static class Name {
public String firstName;
public String lastName;
public Name() {
}
public Name(final String firstName, final String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
}
@@ -0,0 +1,56 @@
package com.baeldung.jackson.annotation;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import com.fasterxml.jackson.annotation.JsonTypeName;
public class Zoo {
public Animal animal;
public Zoo() {
}
public Zoo(final Animal animal) {
this.animal = animal;
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = As.PROPERTY, property = "type")
@JsonSubTypes({ @JsonSubTypes.Type(value = Dog.class, name = "dog"), @JsonSubTypes.Type(value = Cat.class, name = "cat") })
public static class Animal {
public String name;
public Animal() {
}
public Animal(final String name) {
this.name = name;
}
}
@JsonTypeName("dog")
public static class Dog extends Animal {
public double barkVolume;
public Dog() {
}
public Dog(final String name) {
this.name = name;
}
}
@JsonTypeName("cat")
public static class Cat extends Animal {
boolean likesCream;
public int lives;
public Cat() {
}
public Cat(final String name) {
this.name = name;
}
}
}
@@ -0,0 +1,21 @@
package com.baeldung.jackson.annotation.bidirection;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class ItemWithIdentity {
public int id;
public String itemName;
public UserWithIdentity owner;
public ItemWithIdentity() {
super();
}
public ItemWithIdentity(final int id, final String itemName, final UserWithIdentity owner) {
this.id = id;
this.itemName = itemName;
this.owner = owner;
}
}
@@ -0,0 +1,17 @@
package com.baeldung.jackson.annotation.bidirection;
public class ItemWithIgnore {
public int id;
public String itemName;
public UserWithIgnore owner;
public ItemWithIgnore() {
super();
}
public ItemWithIgnore(final int id, final String itemName, final UserWithIgnore owner) {
this.id = id;
this.itemName = itemName;
this.owner = owner;
}
}
@@ -0,0 +1,21 @@
package com.baeldung.jackson.annotation.bidirection;
import com.fasterxml.jackson.annotation.JsonManagedReference;
public class ItemWithRef {
public int id;
public String itemName;
@JsonManagedReference
public UserWithRef owner;
public ItemWithRef() {
super();
}
public ItemWithRef(final int id, final String itemName, final UserWithRef owner) {
this.id = id;
this.itemName = itemName;
this.owner = owner;
}
}
@@ -0,0 +1,28 @@
package com.baeldung.jackson.annotation.bidirection;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class UserWithIdentity {
public int id;
public String name;
public List<ItemWithIdentity> userItems;
public UserWithIdentity() {
super();
}
public UserWithIdentity(final int id, final String name) {
this.id = id;
this.name = name;
userItems = new ArrayList<ItemWithIdentity>();
}
public void addItem(final ItemWithIdentity item) {
userItems.add(item);
}
}
@@ -0,0 +1,28 @@
package com.baeldung.jackson.annotation.bidirection;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class UserWithIgnore {
public int id;
public String name;
@JsonIgnore
public List<ItemWithIgnore> userItems;
public UserWithIgnore() {
super();
}
public UserWithIgnore(final int id, final String name) {
this.id = id;
this.name = name;
userItems = new ArrayList<ItemWithIgnore>();
}
public void addItem(final ItemWithIgnore item) {
userItems.add(item);
}
}
@@ -0,0 +1,28 @@
package com.baeldung.jackson.annotation.bidirection;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonBackReference;
public class UserWithRef {
public int id;
public String name;
@JsonBackReference
public List<ItemWithRef> userItems;
public UserWithRef() {
super();
}
public UserWithRef(final int id, final String name) {
this.id = id;
this.name = name;
userItems = new ArrayList<ItemWithRef>();
}
public void addItem(final ItemWithRef item) {
userItems.add(item);
}
}
@@ -0,0 +1,36 @@
package com.baeldung.jackson.annotation.date;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
public class CustomDateDeserializer extends StdDeserializer<Date> {
private static final long serialVersionUID = -5451717385630622729L;
private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
public CustomDateDeserializer() {
this(null);
}
public CustomDateDeserializer(final Class<?> vc) {
super(vc);
}
@Override
public Date deserialize(final JsonParser jsonparser, final DeserializationContext context) throws IOException, JsonProcessingException {
final String date = jsonparser.getText();
try {
return formatter.parse(date);
} catch (final ParseException e) {
throw new RuntimeException(e);
}
}
}
@@ -0,0 +1,29 @@
package com.baeldung.jackson.annotation.date;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class CustomDateSerializer extends StdSerializer<Date> {
private static final long serialVersionUID = -2894356342227378312L;
private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
public CustomDateSerializer() {
this(null);
}
public CustomDateSerializer(final Class<Date> t) {
super(t);
}
@Override
public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException, JsonProcessingException {
gen.writeString(formatter.format(value));
}
}
@@ -0,0 +1,29 @@
package com.baeldung.jackson.annotation.date;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
public class EventWithFormat {
public String name;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
public Date eventDate;
public EventWithFormat() {
super();
}
public EventWithFormat(final String name, final Date eventDate) {
this.name = name;
this.eventDate = eventDate;
}
public Date getEventDate() {
return eventDate;
}
public String getName() {
return name;
}
}
@@ -0,0 +1,31 @@
package com.baeldung.jackson.annotation.date;
import java.util.Date;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
public class EventWithSerializer {
public String name;
@JsonDeserialize(using = CustomDateDeserializer.class)
@JsonSerialize(using = CustomDateSerializer.class)
public Date eventDate;
public EventWithSerializer() {
super();
}
public EventWithSerializer(final String name, final Date eventDate) {
this.name = name;
this.eventDate = eventDate;
}
public Date getEventDate() {
return eventDate;
}
public String getName() {
return name;
}
}
@@ -0,0 +1,41 @@
package com.baeldung.jackson.annotation.deserialization;
import java.io.IOException;
import com.baeldung.jackson.annotation.dtos.ItemWithSerializer;
import com.baeldung.jackson.annotation.dtos.User;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.node.IntNode;
public class ItemDeserializerOnClass extends StdDeserializer<ItemWithSerializer> {
private static final long serialVersionUID = 5579141241817332594L;
public ItemDeserializerOnClass() {
this(null);
}
public ItemDeserializerOnClass(final Class<?> vc) {
super(vc);
}
/**
* {"id":1,"itemNr":"theItem","owner":2}
*/
@Override
public ItemWithSerializer deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
final JsonNode node = jp.getCodec()
.readTree(jp);
final int id = (Integer) ((IntNode) node.get("id")).numberValue();
final String itemName = node.get("itemName")
.asText();
final int userId = (Integer) ((IntNode) node.get("owner")).numberValue();
return new ItemWithSerializer(id, itemName, new User(userId, null));
}
}
@@ -0,0 +1,32 @@
package com.baeldung.jackson.annotation.dtos;
public class Item {
public int id;
public String itemName;
public User owner;
public Item() {
super();
}
public Item(final int id, final String itemName, final User owner) {
this.id = id;
this.itemName = itemName;
this.owner = owner;
}
// API
public int getId() {
return id;
}
public String getItemName() {
return itemName;
}
public User getOwner() {
return owner;
}
}
@@ -0,0 +1,36 @@
package com.baeldung.jackson.annotation.dtos;
import com.baeldung.jackson.annotation.deserialization.ItemDeserializerOnClass;
import com.baeldung.jackson.annotation.serialization.ItemSerializerOnClass;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonSerialize(using = ItemSerializerOnClass.class)
@JsonDeserialize(using = ItemDeserializerOnClass.class)
public class ItemWithSerializer {
public final int id;
public final String itemName;
public final User owner;
public ItemWithSerializer(final int id, final String itemName, final User owner) {
this.id = id;
this.itemName = itemName;
this.owner = owner;
}
// API
public int getId() {
return id;
}
public String getItemName() {
return itemName;
}
public User getOwner() {
return owner;
}
}
@@ -0,0 +1,26 @@
package com.baeldung.jackson.annotation.dtos;
public class User {
public int id;
public String name;
public User() {
super();
}
public User(final int id, final String name) {
this.id = id;
this.name = name;
}
// API
public int getId() {
return id;
}
public String getName() {
return name;
}
}
@@ -0,0 +1,29 @@
package com.baeldung.jackson.annotation.dtos.withEnum;
import com.fasterxml.jackson.annotation.JsonValue;
public enum DistanceEnumWithValue {
KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001);
private String unit;
private final double meters;
private DistanceEnumWithValue(String unit, double meters) {
this.unit = unit;
this.meters = meters;
}
@JsonValue
public double getMeters() {
return meters;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
}
@@ -0,0 +1,18 @@
package com.baeldung.jackson.annotation.exception;
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName(value = "user")
public class UserWithRoot {
public int id;
public String name;
public UserWithRoot() {
super();
}
public UserWithRoot(final int id, final String name) {
this.id = id;
this.name = name;
}
}
@@ -0,0 +1,18 @@
package com.baeldung.jackson.annotation.exception;
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName(value = "user", namespace="users")
public class UserWithRootNamespace {
public int id;
public String name;
public UserWithRootNamespace() {
super();
}
public UserWithRootNamespace(final int id, final String name) {
this.id = id;
this.name = name;
}
}
@@ -0,0 +1,36 @@
package com.baeldung.jackson.annotation.jsonview;
import com.fasterxml.jackson.annotation.JsonView;
public class Item {
@JsonView(Views.Public.class)
public int id;
@JsonView(Views.Public.class)
public String itemName;
@JsonView(Views.Internal.class)
public String ownerName;
public Item() {
super();
}
public Item(final int id, final String itemName, final String ownerName) {
this.id = id;
this.itemName = itemName;
this.ownerName = ownerName;
}
public int getId() {
return id;
}
public String getItemName() {
return itemName;
}
public String getOwnerName() {
return ownerName;
}
}
@@ -0,0 +1,9 @@
package com.baeldung.jackson.annotation.jsonview;
public class Views {
public static class Public {
}
public static class Internal extends Public {
}
}
@@ -0,0 +1,32 @@
package com.baeldung.jackson.annotation.serialization;
import java.io.IOException;
import com.baeldung.jackson.annotation.dtos.Item;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class ItemSerializer extends StdSerializer<Item> {
private static final long serialVersionUID = 6739170890621978901L;
public ItemSerializer() {
this(null);
}
public ItemSerializer(final Class<Item> t) {
super(t);
}
@Override
public final void serialize(final Item value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeNumberField("id", value.id);
jgen.writeStringField("itemName", value.itemName);
jgen.writeNumberField("owner", value.owner.id);
jgen.writeEndObject();
}
}
@@ -0,0 +1,32 @@
package com.baeldung.jackson.annotation.serialization;
import java.io.IOException;
import com.baeldung.jackson.annotation.dtos.ItemWithSerializer;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class ItemSerializerOnClass extends StdSerializer<ItemWithSerializer> {
private static final long serialVersionUID = -1760959597313610409L;
public ItemSerializerOnClass() {
this(null);
}
public ItemSerializerOnClass(final Class<ItemWithSerializer> t) {
super(t);
}
@Override
public final void serialize(final ItemWithSerializer value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeNumberField("id", value.id);
jgen.writeStringField("itemName", value.itemName);
jgen.writeNumberField("owner", value.owner.id);
jgen.writeEndObject();
}
}
@@ -0,0 +1,29 @@
package com.baeldung.jackson.bidirection;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
public class CustomListDeserializer extends StdDeserializer<List<ItemWithSerializer>> {
private static final long serialVersionUID = 1095767961632979804L;
public CustomListDeserializer() {
this(null);
}
public CustomListDeserializer(final Class<?> vc) {
super(vc);
}
@Override
public List<ItemWithSerializer> deserialize(final JsonParser jsonparser, final DeserializationContext context) throws IOException, JsonProcessingException {
return new ArrayList<ItemWithSerializer>();
}
}
@@ -0,0 +1,32 @@
package com.baeldung.jackson.bidirection;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class CustomListSerializer extends StdSerializer<List<ItemWithSerializer>> {
private static final long serialVersionUID = 3698763098000900856L;
public CustomListSerializer() {
this(null);
}
public CustomListSerializer(final Class<List<ItemWithSerializer>> t) {
super(t);
}
@Override
public void serialize(final List<ItemWithSerializer> items, final JsonGenerator generator, final SerializerProvider provider) throws IOException, JsonProcessingException {
final List<Integer> ids = new ArrayList<Integer>();
for (final ItemWithSerializer item : items) {
ids.add(item.id);
}
generator.writeObject(ids);
}
}
@@ -0,0 +1,17 @@
package com.baeldung.jackson.bidirection;
public class Item {
public int id;
public String itemName;
public User owner;
public Item() {
super();
}
public Item(final int id, final String itemName, final User owner) {
this.id = id;
this.itemName = itemName;
this.owner = owner;
}
}
@@ -0,0 +1,21 @@
package com.baeldung.jackson.bidirection;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class ItemWithIdentity {
public int id;
public String itemName;
public UserWithIdentity owner;
public ItemWithIdentity() {
super();
}
public ItemWithIdentity(final int id, final String itemName, final UserWithIdentity owner) {
this.id = id;
this.itemName = itemName;
this.owner = owner;
}
}
@@ -0,0 +1,17 @@
package com.baeldung.jackson.bidirection;
public class ItemWithIgnore {
public int id;
public String itemName;
public UserWithIgnore owner;
public ItemWithIgnore() {
super();
}
public ItemWithIgnore(final int id, final String itemName, final UserWithIgnore owner) {
this.id = id;
this.itemName = itemName;
this.owner = owner;
}
}
@@ -0,0 +1,21 @@
package com.baeldung.jackson.bidirection;
import com.fasterxml.jackson.annotation.JsonManagedReference;
public class ItemWithRef {
public int id;
public String itemName;
@JsonManagedReference
public UserWithRef owner;
public ItemWithRef() {
super();
}
public ItemWithRef(final int id, final String itemName, final UserWithRef owner) {
this.id = id;
this.itemName = itemName;
this.owner = owner;
}
}
@@ -0,0 +1,17 @@
package com.baeldung.jackson.bidirection;
public class ItemWithSerializer {
public int id;
public String itemName;
public UserWithSerializer owner;
public ItemWithSerializer() {
super();
}
public ItemWithSerializer(final int id, final String itemName, final UserWithSerializer owner) {
this.id = id;
this.itemName = itemName;
this.owner = owner;
}
}
@@ -0,0 +1,26 @@
package com.baeldung.jackson.bidirection;
import com.baeldung.jackson.bidirection.jsonview.Views;
import com.fasterxml.jackson.annotation.JsonView;
public class ItemWithView {
@JsonView(Views.Public.class)
public int id;
@JsonView(Views.Public.class)
public String itemName;
@JsonView(Views.Public.class)
public UserWithView owner;
public ItemWithView() {
super();
}
public ItemWithView(final int id, final String itemName, final UserWithView owner) {
this.id = id;
this.itemName = itemName;
this.owner = owner;
}
}
@@ -0,0 +1,24 @@
package com.baeldung.jackson.bidirection;
import java.util.ArrayList;
import java.util.List;
public class User {
public int id;
public String name;
public List<Item> userItems;
public User() {
super();
}
public User(final int id, final String name) {
this.id = id;
this.name = name;
userItems = new ArrayList<Item>();
}
public void addItem(final Item item) {
userItems.add(item);
}
}
@@ -0,0 +1,28 @@
package com.baeldung.jackson.bidirection;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class UserWithIdentity {
public int id;
public String name;
public List<ItemWithIdentity> userItems;
public UserWithIdentity() {
super();
}
public UserWithIdentity(final int id, final String name) {
this.id = id;
this.name = name;
userItems = new ArrayList<ItemWithIdentity>();
}
public void addItem(final ItemWithIdentity item) {
userItems.add(item);
}
}
@@ -0,0 +1,28 @@
package com.baeldung.jackson.bidirection;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class UserWithIgnore {
public int id;
public String name;
@JsonIgnore
public List<ItemWithIgnore> userItems;
public UserWithIgnore() {
super();
}
public UserWithIgnore(final int id, final String name) {
this.id = id;
this.name = name;
userItems = new ArrayList<ItemWithIgnore>();
}
public void addItem(final ItemWithIgnore item) {
userItems.add(item);
}
}
@@ -0,0 +1,28 @@
package com.baeldung.jackson.bidirection;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonBackReference;
public class UserWithRef {
public int id;
public String name;
@JsonBackReference
public List<ItemWithRef> userItems;
public UserWithRef() {
super();
}
public UserWithRef(final int id, final String name) {
this.id = id;
this.name = name;
userItems = new ArrayList<ItemWithRef>();
}
public void addItem(final ItemWithRef item) {
userItems.add(item);
}
}
@@ -0,0 +1,30 @@
package com.baeldung.jackson.bidirection;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
public class UserWithSerializer {
public int id;
public String name;
@JsonSerialize(using = CustomListSerializer.class)
@JsonDeserialize(using = CustomListDeserializer.class)
public List<ItemWithSerializer> userItems;
public UserWithSerializer() {
super();
}
public UserWithSerializer(final int id, final String name) {
this.id = id;
this.name = name;
userItems = new ArrayList<ItemWithSerializer>();
}
public void addItem(final ItemWithSerializer item) {
userItems.add(item);
}
}
@@ -0,0 +1,33 @@
package com.baeldung.jackson.bidirection;
import java.util.ArrayList;
import java.util.List;
import com.baeldung.jackson.bidirection.jsonview.Views;
import com.fasterxml.jackson.annotation.JsonView;
public class UserWithView {
@JsonView(Views.Public.class)
public int id;
@JsonView(Views.Public.class)
public String name;
@JsonView(Views.Internal.class)
public List<ItemWithView> userItems;
public UserWithView() {
super();
}
public UserWithView(final int id, final String name) {
this.id = id;
this.name = name;
userItems = new ArrayList<ItemWithView>();
}
public void addItem(final ItemWithView item) {
userItems.add(item);
}
}
@@ -0,0 +1,9 @@
package com.baeldung.jackson.bidirection.jsonview;
public class Views {
public static class Public {
}
public static class Internal extends Public {
}
}
@@ -0,0 +1,30 @@
package com.baeldung.jackson.domain;
public class Person {
private String firstName;
private String lastName;
public Person(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
@@ -0,0 +1,37 @@
package com.baeldung.jackson.format;
import java.util.Date;
import com.baeldung.jackson.domain.Person;
import com.fasterxml.jackson.annotation.JsonFormat;
/**
* @author Jay Sridhar
* @version 1.0
*/
public class User extends Person {
private String firstName;
private String lastName;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ")
private Date createdDate;
public User(String firstName, String lastName) {
super(firstName, lastName);
this.createdDate = new Date();
}
public Date getCreatedDate() {
return createdDate;
}
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ", locale = "en_GB")
public Date getCurrentDate() {
return new Date();
}
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
public Date getDateNum() {
return new Date();
}
}
@@ -0,0 +1,133 @@
package com.baeldung.jackson.advancedannotations;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.baeldung.jackson.advancedannotations.AppendBeans.BeanWithAppend;
import com.baeldung.jackson.advancedannotations.AppendBeans.BeanWithoutAppend;
import com.baeldung.jackson.advancedannotations.IdentityReferenceBeans.BeanWithIdentityReference;
import com.baeldung.jackson.advancedannotations.IdentityReferenceBeans.BeanWithoutIdentityReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.module.jsonSchema.JsonSchema;
import com.fasterxml.jackson.module.jsonSchema.factories.SchemaFactoryWrapper;
public class AdvancedAnnotationsUnitTest {
@Test
public void whenNotUsingJsonIdentityReferenceAnnotation_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
BeanWithoutIdentityReference bean = new BeanWithoutIdentityReference(1, "Bean Without Identity Reference Annotation");
String jsonString = mapper.writeValueAsString(bean);
assertThat(jsonString, containsString("Bean Without Identity Reference Annotation"));
}
@Test
public void whenUsingJsonIdentityReferenceAnnotation_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
BeanWithIdentityReference bean = new BeanWithIdentityReference(1, "Bean With Identity Reference Annotation");
String jsonString = mapper.writeValueAsString(bean);
assertEquals("1", jsonString);
}
@Test
public void whenNotUsingJsonAppendAnnotation_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
BeanWithoutAppend bean = new BeanWithoutAppend(2, "Bean Without Append Annotation");
ObjectWriter writer = mapper.writerFor(BeanWithoutAppend.class)
.withAttribute("version", "1.0");
String jsonString = writer.writeValueAsString(bean);
assertThat(jsonString, not(containsString("version")));
assertThat(jsonString, not(containsString("1.0")));
}
@Test
public void whenUsingJsonAppendAnnotation_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
BeanWithAppend bean = new BeanWithAppend(2, "Bean With Append Annotation");
ObjectWriter writer = mapper.writerFor(BeanWithAppend.class)
.withAttribute("version", "1.0");
String jsonString = writer.writeValueAsString(bean);
assertThat(jsonString, containsString("version"));
assertThat(jsonString, containsString("1.0"));
}
@Test
public void whenUsingJsonNamingAnnotation_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
NamingBean bean = new NamingBean(3, "Naming Bean");
String jsonString = mapper.writeValueAsString(bean);
assertThat(jsonString, containsString("bean_name"));
}
@Test
public void whenUsingJsonPropertyDescriptionAnnotation_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
SchemaFactoryWrapper wrapper = new SchemaFactoryWrapper();
mapper.acceptJsonFormatVisitor(PropertyDescriptionBean.class, wrapper);
JsonSchema jsonSchema = wrapper.finalSchema();
String jsonString = mapper.writeValueAsString(jsonSchema);
System.out.println(jsonString);
assertThat(jsonString, containsString("This is a description of the name property"));
}
@Test
public void whenUsingJsonPOJOBuilderAnnotation_thenCorrect() throws IOException {
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"id\":5,\"name\":\"POJO Builder Bean\"}";
POJOBuilderBean bean = mapper.readValue(jsonString, POJOBuilderBean.class);
assertEquals(5, bean.getIdentity());
assertEquals("POJO Builder Bean", bean.getBeanName());
}
@Test
public void whenUsingJsonTypeIdAnnotation_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping(DefaultTyping.NON_FINAL);
TypeIdBean bean = new TypeIdBean(6, "Type Id Bean");
String jsonString = mapper.writeValueAsString(bean);
assertThat(jsonString, containsString("Type Id Bean"));
}
@Test
public void whenUsingJsonTypeIdResolverAnnotation_thenCorrect() throws IOException {
TypeIdResolverStructure.FirstBean bean1 = new TypeIdResolverStructure.FirstBean(1, "Bean 1");
TypeIdResolverStructure.LastBean bean2 = new TypeIdResolverStructure.LastBean(2, "Bean 2");
List<TypeIdResolverStructure.AbstractBean> beans = new ArrayList<>();
beans.add(bean1);
beans.add(bean2);
TypeIdResolverStructure.BeanContainer serializedContainer = new TypeIdResolverStructure.BeanContainer();
serializedContainer.setBeans(beans);
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(serializedContainer);
assertThat(jsonString, containsString("bean1"));
assertThat(jsonString, containsString("bean2"));
TypeIdResolverStructure.BeanContainer deserializedContainer = mapper.readValue(jsonString, TypeIdResolverStructure.BeanContainer.class);
List<TypeIdResolverStructure.AbstractBean> beanList = deserializedContainer.getBeans();
assertThat(beanList.get(0), instanceOf(TypeIdResolverStructure.FirstBean.class));
assertThat(beanList.get(1), instanceOf(TypeIdResolverStructure.LastBean.class));
}
}
@@ -0,0 +1,58 @@
package com.baeldung.jackson.advancedannotations;
import com.fasterxml.jackson.databind.annotation.JsonAppend;
public class AppendBeans {
public static class BeanWithoutAppend {
private int id;
private String name;
public BeanWithoutAppend(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@JsonAppend(attrs = { @JsonAppend.Attr(value = "version") })
public static class BeanWithAppend {
private int id;
private String name;
public BeanWithAppend(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
@@ -0,0 +1,62 @@
package com.baeldung.jackson.advancedannotations;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIdentityReference;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
public class IdentityReferenceBeans {
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public static class BeanWithoutIdentityReference {
private int id;
private String name;
public BeanWithoutIdentityReference(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIdentityReference(alwaysAsId = true)
public static class BeanWithIdentityReference {
private int id;
private String name;
public BeanWithIdentityReference(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
@@ -0,0 +1,31 @@
package com.baeldung.jackson.advancedannotations;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class NamingBean {
private int id;
private String beanName;
public NamingBean(int id, String beanName) {
this.id = id;
this.beanName = beanName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBeanName() {
return beanName;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
}
@@ -0,0 +1,51 @@
package com.baeldung.jackson.advancedannotations;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
@JsonDeserialize(builder = POJOBuilderBean.BeanBuilder.class)
public class POJOBuilderBean {
private int identity;
private String beanName;
@JsonPOJOBuilder(buildMethodName = "createBean", withPrefix = "construct")
public static class BeanBuilder {
private int idValue;
private String nameValue;
public BeanBuilder constructId(int id) {
idValue = id;
return this;
}
public BeanBuilder constructName(String name) {
nameValue = name;
return this;
}
public POJOBuilderBean createBean() {
return new POJOBuilderBean(idValue, nameValue);
}
}
public POJOBuilderBean(int identity, String beanName) {
this.identity = identity;
this.beanName = beanName;
}
public int getIdentity() {
return identity;
}
public void setIdentity(int identity) {
this.identity = identity;
}
public String getBeanName() {
return beanName;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
}
@@ -0,0 +1,25 @@
package com.baeldung.jackson.advancedannotations;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
public class PropertyDescriptionBean {
private int id;
@JsonPropertyDescription("This is a description of the name property")
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,30 @@
package com.baeldung.jackson.advancedannotations;
import com.fasterxml.jackson.annotation.JsonTypeId;
public class TypeIdBean {
private int id;
@JsonTypeId
private String name;
public TypeIdBean(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,130 @@
package com.baeldung.jackson.advancedannotations;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
import com.fasterxml.jackson.databind.DatabindContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.annotation.JsonTypeIdResolver;
import com.fasterxml.jackson.databind.jsontype.impl.TypeIdResolverBase;
public class TypeIdResolverStructure {
public static class BeanContainer {
private List<AbstractBean> beans;
public List<AbstractBean> getBeans() {
return beans;
}
public void setBeans(List<AbstractBean> beans) {
this.beans = beans;
}
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@type")
@JsonTypeIdResolver(BeanIdResolver.class)
public static class AbstractBean {
private int id;
protected AbstractBean() {
}
protected AbstractBean(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
public static class FirstBean extends AbstractBean {
String firstName;
public FirstBean() {
}
public FirstBean(int id, String name) {
super(id);
setFirstName(name);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String name) {
firstName = name;
}
}
public static class LastBean extends AbstractBean {
String lastName;
public LastBean() {
}
public LastBean(int id, String name) {
super(id);
setLastName(name);
}
public String getLastName() {
return lastName;
}
public void setLastName(String name) {
lastName = name;
}
}
public static class BeanIdResolver extends TypeIdResolverBase {
private JavaType superType;
@Override
public void init(JavaType baseType) {
superType = baseType;
}
@Override
public Id getMechanism() {
return Id.NAME;
}
@Override
public String idFromValue(Object obj) {
return idFromValueAndType(obj, obj.getClass());
}
@Override
public String idFromValueAndType(Object obj, Class<?> subType) {
String typeId = null;
switch (subType.getSimpleName()) {
case "FirstBean":
typeId = "bean1";
break;
case "LastBean":
typeId = "bean2";
}
return typeId;
}
@Override
public JavaType typeFromId(DatabindContext context, String id) {
Class<?> subType = null;
switch (id) {
case "bean1":
subType = FirstBean.class;
break;
case "bean2":
subType = LastBean.class;
}
return context.constructSpecializedType(superType, subType);
}
}
}
@@ -0,0 +1,405 @@
package com.baeldung.jackson.annotation;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import org.junit.Test;
import com.baeldung.jackson.annotation.bidirection.ItemWithIdentity;
import com.baeldung.jackson.annotation.bidirection.ItemWithRef;
import com.baeldung.jackson.annotation.bidirection.UserWithIdentity;
import com.baeldung.jackson.annotation.bidirection.UserWithRef;
import com.baeldung.jackson.annotation.date.EventWithFormat;
import com.baeldung.jackson.annotation.date.EventWithSerializer;
import com.baeldung.jackson.ignore.dtos.MyMixInForIgnoreType;
import com.baeldung.jackson.annotation.dtos.withEnum.DistanceEnumWithValue;
import com.baeldung.jackson.annotation.exception.UserWithRoot;
import com.baeldung.jackson.annotation.exception.UserWithRootNamespace;
import com.baeldung.jackson.annotation.jsonview.Item;
import com.baeldung.jackson.annotation.jsonview.Views;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.InjectableValues;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
public class JacksonAnnotationUnitTest {
@Test
public void whenSerializingUsingJsonAnyGetter_thenCorrect() throws JsonProcessingException {
final ExtendableBean bean = new ExtendableBean("My bean");
bean.add("attr1", "val1");
bean.add("attr2", "val2");
final String result = new ObjectMapper().writeValueAsString(bean);
assertThat(result, containsString("attr1"));
assertThat(result, containsString("val1"));
}
@Test
public void whenSerializingUsingJsonGetter_thenCorrect() throws JsonProcessingException {
final BeanWithGetter bean = new BeanWithGetter(1, "My bean");
final String result = new ObjectMapper().writeValueAsString(bean);
assertThat(result, containsString("My bean"));
assertThat(result, containsString("1"));
}
@Test
public void whenSerializingUsingJsonPropertyOrder_thenCorrect() throws JsonProcessingException {
final MyBean bean = new MyBean(1, "My bean");
final String result = new ObjectMapper().writeValueAsString(bean);
assertThat(result, containsString("My bean"));
assertThat(result, containsString("1"));
}
@Test
public void whenSerializingUsingJsonRawValue_thenCorrect() throws JsonProcessingException {
final RawBean bean = new RawBean("My bean", "{\"attr\":false}");
final String result = new ObjectMapper().writeValueAsString(bean);
assertThat(result, containsString("My bean"));
assertThat(result, containsString("{\"attr\":false}"));
}
@Test
public void whenSerializingUsingJsonRootName_thenCorrect() throws JsonProcessingException {
final UserWithRoot user = new UserWithRoot(1, "John");
final ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
final String result = mapper.writeValueAsString(user);
assertThat(result, containsString("John"));
assertThat(result, containsString("user"));
}
@Test
public void whenSerializingUsingJsonValue_thenCorrect() throws IOException {
final String enumAsString = new ObjectMapper().writeValueAsString(DistanceEnumWithValue.MILE);
assertThat(enumAsString, is("1609.34"));
}
@Test
public void whenSerializingUsingJsonSerialize_thenCorrect() throws JsonProcessingException, ParseException {
final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
final String toParse = "20-12-2014 02:30:00";
final Date date = df.parse(toParse);
final EventWithSerializer event = new EventWithSerializer("party", date);
final String result = new ObjectMapper().writeValueAsString(event);
assertThat(result, containsString(toParse));
}
// ========================= Deserializing annotations ============================
@Test
public void whenDeserializingUsingJsonCreator_thenCorrect() throws IOException {
final String json = "{\"id\":1,\"theName\":\"My bean\"}";
final BeanWithCreator bean = new ObjectMapper().readerFor(BeanWithCreator.class)
.readValue(json);
assertEquals("My bean", bean.name);
}
@Test
public void whenDeserializingUsingJsonInject_thenCorrect() throws IOException {
final String json = "{\"name\":\"My bean\"}";
final InjectableValues inject = new InjectableValues.Std().addValue(int.class, 1);
final BeanWithInject bean = new ObjectMapper().reader(inject)
.forType(BeanWithInject.class)
.readValue(json);
assertEquals("My bean", bean.name);
assertEquals(1, bean.id);
}
@Test
public void whenDeserializingUsingJsonAnySetter_thenCorrect() throws IOException {
final String json = "{\"name\":\"My bean\",\"attr2\":\"val2\",\"attr1\":\"val1\"}";
final ExtendableBean bean = new ObjectMapper().readerFor(ExtendableBean.class)
.readValue(json);
assertEquals("My bean", bean.name);
assertEquals("val2", bean.getProperties()
.get("attr2"));
}
@Test
public void whenDeserializingUsingJsonSetter_thenCorrect() throws IOException {
final String json = "{\"id\":1,\"name\":\"My bean\"}";
final BeanWithGetter bean = new ObjectMapper().readerFor(BeanWithGetter.class)
.readValue(json);
assertEquals("My bean", bean.getTheName());
}
@Test
public void whenDeserializingUsingJsonDeserialize_thenCorrect() throws IOException {
final String json = "{\"name\":\"party\",\"eventDate\":\"20-12-2014 02:30:00\"}";
final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
final EventWithSerializer event = new ObjectMapper().readerFor(EventWithSerializer.class)
.readValue(json);
assertEquals("20-12-2014 02:30:00", df.format(event.eventDate));
}
// ========================= Inclusion annotations ============================
@Test
public void whenSerializingUsingJsonIgnoreProperties_thenCorrect() throws JsonProcessingException {
final BeanWithIgnore bean = new BeanWithIgnore(1, "My bean");
final String result = new ObjectMapper().writeValueAsString(bean);
assertThat(result, containsString("My bean"));
assertThat(result, not(containsString("id")));
}
@Test
public void whenSerializingUsingJsonIgnore_thenCorrect() throws JsonProcessingException {
final BeanWithIgnore bean = new BeanWithIgnore(1, "My bean");
final String result = new ObjectMapper().writeValueAsString(bean);
assertThat(result, containsString("My bean"));
assertThat(result, not(containsString("id")));
}
@Test
public void whenSerializingUsingJsonIgnoreType_thenCorrect() throws JsonProcessingException, ParseException {
final UserWithIgnoreType.Name name = new UserWithIgnoreType.Name("John", "Doe");
final UserWithIgnoreType user = new UserWithIgnoreType(1, name);
final String result = new ObjectMapper().writeValueAsString(user);
assertThat(result, containsString("1"));
assertThat(result, not(containsString("name")));
assertThat(result, not(containsString("John")));
}
@Test
public void whenSerializingUsingJsonInclude_thenCorrect() throws JsonProcessingException {
final MyBean bean = new MyBean(1, null);
final String result = new ObjectMapper().writeValueAsString(bean);
assertThat(result, containsString("1"));
assertThat(result, not(containsString("name")));
}
@Test
public void whenSerializingUsingJsonAutoDetect_thenCorrect() throws JsonProcessingException {
final PrivateBean bean = new PrivateBean(1, "My bean");
final String result = new ObjectMapper().writeValueAsString(bean);
assertThat(result, containsString("1"));
assertThat(result, containsString("My bean"));
}
// ========================= Polymorphic annotations ============================
@Test
public void whenSerializingPolymorphic_thenCorrect() throws JsonProcessingException {
final Zoo.Dog dog = new Zoo.Dog("lacy");
final Zoo zoo = new Zoo(dog);
final String result = new ObjectMapper().writeValueAsString(zoo);
assertThat(result, containsString("type"));
assertThat(result, containsString("dog"));
}
@Test
public void whenDeserializingPolymorphic_thenCorrect() throws IOException {
final String json = "{\"animal\":{\"name\":\"lacy\",\"type\":\"cat\"}}";
final Zoo zoo = new ObjectMapper().readerFor(Zoo.class)
.readValue(json);
assertEquals("lacy", zoo.animal.name);
assertEquals(Zoo.Cat.class, zoo.animal.getClass());
}
// ========================= General annotations ============================
@Test
public void whenUsingJsonProperty_thenCorrect() throws IOException {
final BeanWithGetter bean = new BeanWithGetter(1, "My bean");
final String result = new ObjectMapper().writeValueAsString(bean);
assertThat(result, containsString("My bean"));
assertThat(result, containsString("1"));
final BeanWithGetter resultBean = new ObjectMapper().readerFor(BeanWithGetter.class)
.readValue(result);
assertEquals("My bean", resultBean.getTheName());
}
@Test
public void whenSerializingUsingJsonFormat_thenCorrect() throws JsonProcessingException, ParseException {
final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
final String toParse = "20-12-2014 02:30:00";
final Date date = df.parse(toParse);
final EventWithFormat event = new EventWithFormat("party", date);
final String result = new ObjectMapper().writeValueAsString(event);
assertThat(result, containsString(toParse));
}
@Test
public void whenSerializingUsingJsonUnwrapped_thenCorrect() throws JsonProcessingException, ParseException {
final UnwrappedUser.Name name = new UnwrappedUser.Name("John", "Doe");
final UnwrappedUser user = new UnwrappedUser(1, name);
final String result = new ObjectMapper().writeValueAsString(user);
assertThat(result, containsString("John"));
assertThat(result, not(containsString("name")));
}
@Test
public void whenSerializingUsingJsonView_thenCorrect() throws JsonProcessingException, JsonProcessingException {
final Item item = new Item(2, "book", "John");
final String result = new ObjectMapper().writerWithView(Views.Public.class)
.writeValueAsString(item);
assertThat(result, containsString("book"));
assertThat(result, containsString("2"));
assertThat(result, not(containsString("John")));
}
@Test
public void whenSerializingUsingJacksonReferenceAnnotation_thenCorrect() throws JsonProcessingException {
final UserWithRef user = new UserWithRef(1, "John");
final ItemWithRef item = new ItemWithRef(2, "book", user);
user.addItem(item);
final String result = new ObjectMapper().writeValueAsString(item);
assertThat(result, containsString("book"));
assertThat(result, containsString("John"));
assertThat(result, not(containsString("userItems")));
}
@Test
public void whenSerializingUsingJsonIdentityInfo_thenCorrect() throws JsonProcessingException {
final UserWithIdentity user = new UserWithIdentity(1, "John");
final ItemWithIdentity item = new ItemWithIdentity(2, "book", user);
user.addItem(item);
final String result = new ObjectMapper().writeValueAsString(item);
assertThat(result, containsString("book"));
assertThat(result, containsString("John"));
assertThat(result, containsString("userItems"));
}
@Test
public void whenSerializingUsingJsonFilter_thenCorrect() throws JsonProcessingException {
final BeanWithFilter bean = new BeanWithFilter(1, "My bean");
final FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", SimpleBeanPropertyFilter.filterOutAllExcept("name"));
final String result = new ObjectMapper().writer(filters)
.writeValueAsString(bean);
assertThat(result, containsString("My bean"));
assertThat(result, not(containsString("id")));
}
// =========================
@Test
public void whenSerializingUsingCustomAnnotation_thenCorrect() throws JsonProcessingException {
final BeanWithCustomAnnotation bean = new BeanWithCustomAnnotation(1, "My bean", null);
final String result = new ObjectMapper().writeValueAsString(bean);
assertThat(result, containsString("My bean"));
assertThat(result, containsString("1"));
assertThat(result, not(containsString("dateCreated")));
}
// @Ignore("Jackson 2.7.1-1 seems to have changed the API regarding mixins")
@Test
public void whenSerializingUsingMixInAnnotation_thenCorrect() throws JsonProcessingException {
final com.baeldung.jackson.annotation.dtos.Item item = new com.baeldung.jackson.annotation.dtos.Item(1, "book", null);
String result = new ObjectMapper().writeValueAsString(item);
assertThat(result, containsString("owner"));
final ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(com.baeldung.jackson.annotation.dtos.User.class, MyMixInForIgnoreType.class);
result = mapper.writeValueAsString(item);
assertThat(result, not(containsString("owner")));
}
@Test
public void whenDisablingAllAnnotations_thenAllDisabled() throws JsonProcessingException {
final MyBean bean = new MyBean(1, null);
final ObjectMapper mapper = new ObjectMapper();
mapper.disable(MapperFeature.USE_ANNOTATIONS);
final String result = mapper.writeValueAsString(bean);
assertThat(result, containsString("1"));
assertThat(result, containsString("name"));
}
@Test
public void whenDeserializingUsingJsonAlias_thenCorrect() throws IOException {
// arrange
String json = "{\"fName\": \"John\", \"lastName\": \"Green\"}";
// act
AliasBean aliasBean = new ObjectMapper().readerFor(AliasBean.class).readValue(json);
// assert
assertThat(aliasBean.getFirstName(), is("John"));
}
@Test
public void whenSerializingUsingXMLRootNameWithNameSpace_thenCorrect() throws JsonProcessingException {
// arrange
UserWithRootNamespace author = new UserWithRootNamespace(1, "John");
// act
ObjectMapper mapper = new XmlMapper();
mapper = mapper.enable(SerializationFeature.WRAP_ROOT_VALUE).enable(SerializationFeature.INDENT_OUTPUT);
String result = mapper.writeValueAsString(author);
// assert
assertThat(result, containsString("<user xmlns=\"users\">"));
/*
<user xmlns="users">
<id xmlns="">3006b44a-cf62-4cfe-b3d8-30dc6c46ea96</id>
<id xmlns="">1</id>
<name xmlns="">John</name>
<items xmlns=""/>
</user>
*/
}
}
@@ -0,0 +1,127 @@
package com.baeldung.jackson.bidirection;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import org.junit.Test;
import com.baeldung.jackson.bidirection.jsonview.Views;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonBidirectionRelationUnitTest {
@Test(expected = JsonMappingException.class)
public void givenBidirectionRelation_whenSerializing_thenException() throws JsonProcessingException {
final User user = new User(1, "John");
final Item item = new Item(2, "book", user);
user.addItem(item);
new ObjectMapper().writeValueAsString(item);
}
@Test
public void givenBidirectionRelation_whenUsingJacksonReferenceAnnotation_thenCorrect() throws JsonProcessingException {
final UserWithRef user = new UserWithRef(1, "John");
final ItemWithRef item = new ItemWithRef(2, "book", user);
user.addItem(item);
final String result = new ObjectMapper().writeValueAsString(item);
assertThat(result, containsString("book"));
assertThat(result, containsString("John"));
assertThat(result, not(containsString("userItems")));
}
@Test
public void givenBidirectionRelation_whenUsingJsonIdentityInfo_thenCorrect() throws JsonProcessingException {
final UserWithIdentity user = new UserWithIdentity(1, "John");
final ItemWithIdentity item = new ItemWithIdentity(2, "book", user);
user.addItem(item);
final String result = new ObjectMapper().writeValueAsString(item);
assertThat(result, containsString("book"));
assertThat(result, containsString("John"));
assertThat(result, containsString("userItems"));
}
@Test
public void givenBidirectionRelation_whenUsingJsonIgnore_thenCorrect() throws JsonProcessingException {
final UserWithIgnore user = new UserWithIgnore(1, "John");
final ItemWithIgnore item = new ItemWithIgnore(2, "book", user);
user.addItem(item);
final String result = new ObjectMapper().writeValueAsString(item);
assertThat(result, containsString("book"));
assertThat(result, containsString("John"));
assertThat(result, not(containsString("userItems")));
}
@Test
public void givenBidirectionRelation_whenUsingCustomSerializer_thenCorrect() throws JsonProcessingException {
final UserWithSerializer user = new UserWithSerializer(1, "John");
final ItemWithSerializer item = new ItemWithSerializer(2, "book", user);
user.addItem(item);
final String result = new ObjectMapper().writeValueAsString(item);
assertThat(result, containsString("book"));
assertThat(result, containsString("John"));
assertThat(result, containsString("userItems"));
}
@Test
public void givenBidirectionRelation_whenDeserializingUsingIdentity_thenCorrect() throws JsonProcessingException, IOException {
final String json = "{\"id\":2,\"itemName\":\"book\",\"owner\":{\"id\":1,\"name\":\"John\",\"userItems\":[2]}}";
final ItemWithIdentity item = new ObjectMapper().readerFor(ItemWithIdentity.class)
.readValue(json);
assertEquals(2, item.id);
assertEquals("book", item.itemName);
assertEquals("John", item.owner.name);
}
@Test
public void givenBidirectionRelation_whenUsingCustomDeserializer_thenCorrect() throws JsonProcessingException, IOException {
final String json = "{\"id\":2,\"itemName\":\"book\",\"owner\":{\"id\":1,\"name\":\"John\",\"userItems\":[2]}}";
final ItemWithSerializer item = new ObjectMapper().readerFor(ItemWithSerializer.class)
.readValue(json);
assertEquals(2, item.id);
assertEquals("book", item.itemName);
assertEquals("John", item.owner.name);
}
@Test
public void givenBidirectionRelation_whenUsingPublicJsonView_thenCorrect() throws JsonProcessingException {
final UserWithView user = new UserWithView(1, "John");
final ItemWithView item = new ItemWithView(2, "book", user);
user.addItem(item);
final String result = new ObjectMapper().writerWithView(Views.Public.class)
.writeValueAsString(item);
assertThat(result, containsString("book"));
assertThat(result, containsString("John"));
assertThat(result, not(containsString("userItems")));
}
@Test(expected = JsonMappingException.class)
public void givenBidirectionRelation_whenUsingInternalJsonView_thenException() throws JsonProcessingException {
final UserWithView user = new UserWithView(1, "John");
final ItemWithView item = new ItemWithView(2, "book", user);
user.addItem(item);
new ObjectMapper().writerWithView(Views.Internal.class)
.writeValueAsString(item);
}
}
@@ -0,0 +1,37 @@
package com.baeldung.jackson.format;
import java.util.Date;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import static io.restassured.path.json.JsonPath.from;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.data.Percentage.withPercentage;
/**
* @author Jay Sridhar
* @version 1.0
*/
public class JsonFormatUnitTest {
@Test
public void whenSerializedDateFormat_thenCorrect() throws JsonProcessingException {
User user = new User("Jay", "Sridhar");
String result = new ObjectMapper().writeValueAsString(user);
// Expected to match: "2016-12-19@09:34:42.628+0000"
assertThat(from(result).getString("createdDate")).matches("\\d{4}\\-\\d{2}\\-\\d{2}@\\d{2}:\\d{2}:\\d{2}\\.\\d{3}\\+\\d{4}");
// Expected to be close to current time
long now = new Date().getTime();
assertThat(from(result).getLong("dateNum")).isCloseTo(now, withPercentage(10.0));
}
}
@@ -0,0 +1,278 @@
package com.baeldung.jackson.ignore;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import com.baeldung.jackson.ignore.dtos.MyDto;
import com.baeldung.jackson.ignore.dtos.MyDtoIncludeNonDefault;
import com.baeldung.jackson.ignore.dtos.MyDtoWithFilter;
import com.baeldung.jackson.ignore.dtos.MyDtoWithSpecialField;
import com.baeldung.jackson.ignore.dtos.MyMixInForIgnoreType;
import com.baeldung.jackson.ignore.dtos.MyDtoIgnoreField;
import com.baeldung.jackson.ignore.dtos.MyDtoIgnoreFieldByName;
import com.baeldung.jackson.ignore.dtos.MyDtoIgnoreNull;
import com.baeldung.jackson.ignore.dtos.MyDtoNullKeySerializer;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.PropertyFilter;
import com.fasterxml.jackson.databind.ser.PropertyWriter;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
public class JacksonSerializationIgnoreUnitTest {
// tests - single entity to json
// ignore
@Test
public final void givenOnlyNonDefaultValuesAreSerializedAndDtoHasOnlyDefaultValues_whenSerializing_thenCorrect() throws JsonParseException, IOException {
final ObjectMapper mapper = new ObjectMapper();
final String dtoAsString = mapper.writeValueAsString(new MyDtoIncludeNonDefault());
assertThat(dtoAsString, not(containsString("intValue")));
System.out.println(dtoAsString);
}
@Test
public final void givenOnlyNonDefaultValuesAreSerializedAndDtoHasNonDefaultValue_whenSerializing_thenCorrect() throws JsonParseException, IOException {
final ObjectMapper mapper = new ObjectMapper();
final MyDtoIncludeNonDefault dtoObject = new MyDtoIncludeNonDefault();
dtoObject.setBooleanValue(true);
final String dtoAsString = mapper.writeValueAsString(dtoObject);
assertThat(dtoAsString, containsString("booleanValue"));
System.out.println(dtoAsString);
}
@Test
public final void givenFieldIsIgnoredByName_whenDtoIsSerialized_thenCorrect() throws JsonParseException, IOException {
final ObjectMapper mapper = new ObjectMapper();
final MyDtoIgnoreFieldByName dtoObject = new MyDtoIgnoreFieldByName();
dtoObject.setBooleanValue(true);
final String dtoAsString = mapper.writeValueAsString(dtoObject);
assertThat(dtoAsString, not(containsString("intValue")));
assertThat(dtoAsString, containsString("booleanValue"));
System.out.println(dtoAsString);
}
@Test
public final void givenFieldIsIgnoredDirectly_whenDtoIsSerialized_thenCorrect() throws JsonParseException, IOException {
final ObjectMapper mapper = new ObjectMapper();
final MyDtoIgnoreField dtoObject = new MyDtoIgnoreField();
final String dtoAsString = mapper.writeValueAsString(dtoObject);
assertThat(dtoAsString, not(containsString("intValue")));
assertThat(dtoAsString, containsString("booleanValue"));
System.out.println(dtoAsString);
}
// @Ignore("Jackson 2.7.1-1 seems to have changed the API for this case")
@Test
public final void givenFieldTypeIsIgnored_whenDtoIsSerialized_thenCorrect() throws JsonParseException, IOException {
final ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(String[].class, MyMixInForIgnoreType.class);
final MyDtoWithSpecialField dtoObject = new MyDtoWithSpecialField();
dtoObject.setBooleanValue(true);
final String dtoAsString = mapper.writeValueAsString(dtoObject);
assertThat(dtoAsString, containsString("intValue"));
assertThat(dtoAsString, containsString("booleanValue"));
assertThat(dtoAsString, not(containsString("stringValue")));
System.out.println(dtoAsString);
}
@Test
public final void givenTypeHasFilterThatIgnoresFieldByName_whenDtoIsSerialized_thenCorrect() throws JsonParseException, IOException {
final ObjectMapper mapper = new ObjectMapper();
final SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter.serializeAllExcept("intValue");
final FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", theFilter);
final MyDtoWithFilter dtoObject = new MyDtoWithFilter();
dtoObject.setIntValue(12);
final String dtoAsString = mapper.writer(filters)
.writeValueAsString(dtoObject);
assertThat(dtoAsString, not(containsString("intValue")));
assertThat(dtoAsString, containsString("booleanValue"));
assertThat(dtoAsString, containsString("stringValue"));
System.out.println(dtoAsString);
}
@Test
public final void givenTypeHasFilterThatIgnoresNegativeInt_whenDtoIsSerialized_thenCorrect() throws JsonParseException, IOException {
final PropertyFilter theFilter = new SimpleBeanPropertyFilter() {
@Override
public final void serializeAsField(final Object pojo, final JsonGenerator jgen, final SerializerProvider provider, final PropertyWriter writer) throws Exception {
if (include(writer)) {
if (!writer.getName()
.equals("intValue")) {
writer.serializeAsField(pojo, jgen, provider);
return;
}
final int intValue = ((MyDtoWithFilter) pojo).getIntValue();
if (intValue >= 0) {
writer.serializeAsField(pojo, jgen, provider);
}
} else if (!jgen.canOmitFields()) { // since 2.3
writer.serializeAsOmittedField(pojo, jgen, provider);
}
}
@Override
protected final boolean include(final BeanPropertyWriter writer) {
return true;
}
@Override
protected final boolean include(final PropertyWriter writer) {
return true;
}
};
final FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", theFilter);
final MyDtoWithFilter dtoObject = new MyDtoWithFilter();
dtoObject.setIntValue(-1);
final ObjectMapper mapper = new ObjectMapper();
final String dtoAsString = mapper.writer(filters)
.writeValueAsString(dtoObject);
assertThat(dtoAsString, not(containsString("intValue")));
assertThat(dtoAsString, containsString("booleanValue"));
assertThat(dtoAsString, containsString("stringValue"));
System.out.println(dtoAsString);
}
@Test
public final void givenNullsIgnoredOnClass_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException {
final ObjectMapper mapper = new ObjectMapper();
final MyDtoIgnoreNull dtoObject = new MyDtoIgnoreNull();
final String dtoAsString = mapper.writeValueAsString(dtoObject);
assertThat(dtoAsString, containsString("intValue"));
assertThat(dtoAsString, containsString("booleanValue"));
assertThat(dtoAsString, not(containsString("stringValue")));
System.out.println(dtoAsString);
}
@Test
public final void givenNullsIgnoredGlobally_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException {
final ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
final MyDto dtoObject = new MyDto();
final String dtoAsString = mapper.writeValueAsString(dtoObject);
assertThat(dtoAsString, containsString("intValue"));
assertThat(dtoAsString, containsString("booleanValue"));
assertThat(dtoAsString, not(containsString("stringValue")));
System.out.println(dtoAsString);
}
// map
@Test
public final void givenIgnoringMapNullValue_whenWritingMapObjectWithNullValue_thenIgnored() throws JsonProcessingException {
final ObjectMapper mapper = new ObjectMapper();
// mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
mapper.setSerializationInclusion(Include.NON_NULL);
final MyDto dtoObject1 = new MyDto();
final Map<String, MyDto> dtoMap = new HashMap<String, MyDto>();
dtoMap.put("dtoObject1", dtoObject1);
dtoMap.put("dtoObject2", null);
final String dtoMapAsString = mapper.writeValueAsString(dtoMap);
assertThat(dtoMapAsString, containsString("dtoObject1"));
assertThat(dtoMapAsString, not(containsString("dtoObject2")));
System.out.println(dtoMapAsString);
}
@Test
public final void givenIgnoringMapValueObjectWithNullField_whenWritingMapValueObjectWithNullField_thenIgnored() throws JsonProcessingException {
final ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
final MyDto dtoObject = new MyDto();
final Map<String, MyDto> dtoMap = new HashMap<String, MyDto>();
dtoMap.put("dtoObject", dtoObject);
final String dtoMapAsString = mapper.writeValueAsString(dtoMap);
assertThat(dtoMapAsString, containsString("dtoObject"));
assertThat(dtoMapAsString, not(containsString("stringValue")));
System.out.println(dtoMapAsString);
}
@Test
public final void givenAllowingMapObjectWithNullKey_whenWriting_thenCorrect() throws JsonProcessingException {
final ObjectMapper mapper = new ObjectMapper();
mapper.getSerializerProvider()
.setNullKeySerializer(new MyDtoNullKeySerializer());
final MyDto dtoObject1 = new MyDto();
dtoObject1.setStringValue("dtoObjectString1");
final MyDto dtoObject2 = new MyDto();
dtoObject2.setStringValue("dtoObjectString2");
final Map<String, MyDto> dtoMap = new HashMap<String, MyDto>();
dtoMap.put(null, dtoObject1);
dtoMap.put("obj2", dtoObject2);
final String dtoMapAsString = mapper.writeValueAsString(dtoMap);
System.out.println(dtoMapAsString);
assertThat(dtoMapAsString, containsString("\"\""));
assertThat(dtoMapAsString, containsString("dtoObjectString1"));
assertThat(dtoMapAsString, containsString("obj2"));
}
@Test
public final void givenAllowingMapObjectOneNullKey_whenWritingMapObjectWithTwoNullKeys_thenOverride() throws JsonProcessingException {
final ObjectMapper mapper = new ObjectMapper();
mapper.getSerializerProvider()
.setNullKeySerializer(new MyDtoNullKeySerializer());
final MyDto dtoObject1 = new MyDto();
dtoObject1.setStringValue("dtoObject1String");
final MyDto dtoObject2 = new MyDto();
dtoObject2.setStringValue("dtoObject2String");
final Map<String, MyDto> dtoMap = new HashMap<String, MyDto>();
dtoMap.put(null, dtoObject1);
dtoMap.put(null, dtoObject2);
final String dtoMapAsString = mapper.writeValueAsString(dtoMap);
assertThat(dtoMapAsString, not(containsString("dtoObject1String")));
assertThat(dtoMapAsString, containsString("dtoObject2String"));
System.out.println(dtoMapAsString);
}
}
@@ -0,0 +1,54 @@
package com.baeldung.jackson.ignore.dtos;
public class MyDto {
private String stringValue;
private int intValue;
private boolean booleanValue;
public MyDto() {
super();
}
public MyDto(final String stringValue, final int intValue, final boolean booleanValue) {
super();
this.stringValue = stringValue;
this.intValue = intValue;
this.booleanValue = booleanValue;
}
// API
public String getStringValue() {
return stringValue;
}
public void setStringValue(final String stringValue) {
this.stringValue = stringValue;
}
public int getIntValue() {
return intValue;
}
public void setIntValue(final int intValue) {
this.intValue = intValue;
}
public boolean isBooleanValue() {
return booleanValue;
}
public void setBooleanValue(final boolean booleanValue) {
this.booleanValue = booleanValue;
}
//
@Override
public String toString() {
return "MyDto [stringValue=" + stringValue + ", intValue=" + intValue + ", booleanValue=" + booleanValue + "]";
}
}
@@ -0,0 +1,42 @@
package com.baeldung.jackson.ignore.dtos;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class MyDtoIgnoreField {
private String stringValue;
@JsonIgnore
private int intValue;
private boolean booleanValue;
public MyDtoIgnoreField() {
super();
}
// API
public String getStringValue() {
return stringValue;
}
public void setStringValue(final String stringValue) {
this.stringValue = stringValue;
}
public int getIntValue() {
return intValue;
}
public void setIntValue(final int intValue) {
this.intValue = intValue;
}
public boolean isBooleanValue() {
return booleanValue;
}
public void setBooleanValue(final boolean booleanValue) {
this.booleanValue = booleanValue;
}
}
@@ -0,0 +1,42 @@
package com.baeldung.jackson.ignore.dtos;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(value = { "intValue" })
public class MyDtoIgnoreFieldByName {
private String stringValue;
private int intValue;
private boolean booleanValue;
public MyDtoIgnoreFieldByName() {
super();
}
// API
public String getStringValue() {
return stringValue;
}
public void setStringValue(final String stringValue) {
this.stringValue = stringValue;
}
public int getIntValue() {
return intValue;
}
public void setIntValue(final int intValue) {
this.intValue = intValue;
}
public boolean isBooleanValue() {
return booleanValue;
}
public void setBooleanValue(final boolean booleanValue) {
this.booleanValue = booleanValue;
}
}
@@ -0,0 +1,51 @@
package com.baeldung.jackson.ignore.dtos;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
@JsonInclude(Include.NON_NULL)
public class MyDtoIgnoreNull {
private String stringValue;
private int intValue;
private boolean booleanValue;
public MyDtoIgnoreNull() {
super();
}
public MyDtoIgnoreNull(final String stringValue, final int intValue, final boolean booleanValue) {
super();
this.stringValue = stringValue;
this.intValue = intValue;
this.booleanValue = booleanValue;
}
// API
public String getStringValue() {
return stringValue;
}
public void setStringValue(final String stringValue) {
this.stringValue = stringValue;
}
public int getIntValue() {
return intValue;
}
public void setIntValue(final int intValue) {
this.intValue = intValue;
}
public boolean isBooleanValue() {
return booleanValue;
}
public void setBooleanValue(final boolean booleanValue) {
this.booleanValue = booleanValue;
}
}
@@ -0,0 +1,43 @@
package com.baeldung.jackson.ignore.dtos;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
@JsonInclude(Include.NON_DEFAULT)
public class MyDtoIncludeNonDefault {
private String stringValue;
private int intValue;
private boolean booleanValue;
public MyDtoIncludeNonDefault() {
super();
}
// API
public String getStringValue() {
return stringValue;
}
public void setStringValue(final String stringValue) {
this.stringValue = stringValue;
}
public int getIntValue() {
return intValue;
}
public void setIntValue(final int intValue) {
this.intValue = intValue;
}
public boolean isBooleanValue() {
return booleanValue;
}
public void setBooleanValue(final boolean booleanValue) {
this.booleanValue = booleanValue;
}
}
@@ -0,0 +1,27 @@
package com.baeldung.jackson.ignore.dtos;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class MyDtoNullKeySerializer extends StdSerializer<Object> {
private static final long serialVersionUID = -4478531309177369056L;
public MyDtoNullKeySerializer() {
this(null);
}
public MyDtoNullKeySerializer(final Class<Object> t) {
super(t);
}
@Override
public void serialize(final Object value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeFieldName("");
}
}
@@ -0,0 +1,50 @@
package com.baeldung.jackson.ignore.dtos;
import com.fasterxml.jackson.annotation.JsonFilter;
@JsonFilter("myFilter")
public class MyDtoWithFilter {
private String stringValue;
private int intValue;
private boolean booleanValue;
public MyDtoWithFilter() {
super();
}
public MyDtoWithFilter(final String stringValue, final int intValue, final boolean booleanValue) {
super();
this.stringValue = stringValue;
this.intValue = intValue;
this.booleanValue = booleanValue;
}
// API
public String getStringValue() {
return stringValue;
}
public void setStringValue(final String stringValue) {
this.stringValue = stringValue;
}
public int getIntValue() {
return intValue;
}
public void setIntValue(final int intValue) {
this.intValue = intValue;
}
public boolean isBooleanValue() {
return booleanValue;
}
public void setBooleanValue(final boolean booleanValue) {
this.booleanValue = booleanValue;
}
}
@@ -0,0 +1,54 @@
package com.baeldung.jackson.ignore.dtos;
public class MyDtoWithSpecialField {
private String[] stringValue;
private int intValue;
private boolean booleanValue;
public MyDtoWithSpecialField() {
super();
}
public MyDtoWithSpecialField(final String[] stringValue, final int intValue, final boolean booleanValue) {
super();
this.stringValue = stringValue;
this.intValue = intValue;
this.booleanValue = booleanValue;
}
// API
public String[] getStringValue() {
return stringValue;
}
public void setStringValue(final String[] stringValue) {
this.stringValue = stringValue;
}
public int getIntValue() {
return intValue;
}
public void setIntValue(final int intValue) {
this.intValue = intValue;
}
public boolean isBooleanValue() {
return booleanValue;
}
public void setBooleanValue(final boolean booleanValue) {
this.booleanValue = booleanValue;
}
//
@Override
public String toString() {
return "MyDto [stringValue=" + stringValue + ", intValue=" + intValue + ", booleanValue=" + booleanValue + "]";
}
}
@@ -0,0 +1,8 @@
package com.baeldung.jackson.ignore.dtos;
import com.fasterxml.jackson.annotation.JsonIgnoreType;
@JsonIgnoreType
public class MyMixInForIgnoreType {
//
}
@@ -0,0 +1,44 @@
package com.baeldung.jackson.jsonproperty;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.util.List;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
public class JsonPropertyUnitTest {
@Test
public final void whenSerializing_thenCorrect() throws JsonParseException, IOException {
final ObjectMapper mapper = new ObjectMapper();
final String dtoAsString = mapper.writeValueAsString(new MyDto());
assertThat(dtoAsString, containsString("intValue"));
assertThat(dtoAsString, containsString("stringValue"));
assertThat(dtoAsString, containsString("booleanValue"));
}
@Test
public final void givenNameOfFieldIsChangedViaAnnotationOnGetter_whenSerializing_thenCorrect() throws JsonParseException, IOException {
final ObjectMapper mapper = new ObjectMapper();
final MyDtoFieldNameChanged dtoObject = new MyDtoFieldNameChanged();
dtoObject.setStringValue("a");
final String dtoAsString = mapper.writeValueAsString(dtoObject);
assertThat(dtoAsString, not(containsString("stringValue")));
assertThat(dtoAsString, containsString("strVal"));
System.out.println(dtoAsString);
}
}
@@ -0,0 +1,54 @@
package com.baeldung.jackson.jsonproperty;
public class MyDto {
private String stringValue;
private int intValue;
private boolean booleanValue;
public MyDto() {
super();
}
public MyDto(final String stringValue, final int intValue, final boolean booleanValue) {
super();
this.stringValue = stringValue;
this.intValue = intValue;
this.booleanValue = booleanValue;
}
// API
public String getStringValue() {
return stringValue;
}
public void setStringValue(final String stringValue) {
this.stringValue = stringValue;
}
public int getIntValue() {
return intValue;
}
public void setIntValue(final int intValue) {
this.intValue = intValue;
}
public boolean isBooleanValue() {
return booleanValue;
}
public void setBooleanValue(final boolean booleanValue) {
this.booleanValue = booleanValue;
}
//
@Override
public String toString() {
return "MyDto [stringValue=" + stringValue + ", intValue=" + intValue + ", booleanValue=" + booleanValue + "]";
}
}
@@ -0,0 +1,50 @@
package com.baeldung.jackson.jsonproperty;
import com.fasterxml.jackson.annotation.JsonProperty;
public class MyDtoFieldNameChanged {
private String stringValue;
private int intValue;
private boolean booleanValue;
public MyDtoFieldNameChanged() {
super();
}
public MyDtoFieldNameChanged(final String stringValue, final int intValue, final boolean booleanValue) {
super();
this.stringValue = stringValue;
this.intValue = intValue;
this.booleanValue = booleanValue;
}
// API
@JsonProperty("strVal")
public String getStringValue() {
return stringValue;
}
public void setStringValue(final String stringValue) {
this.stringValue = stringValue;
}
public int getIntValue() {
return intValue;
}
public void setIntValue(final int intValue) {
this.intValue = intValue;
}
public boolean isBooleanValue() {
return booleanValue;
}
public void setBooleanValue(final boolean booleanValue) {
this.booleanValue = booleanValue;
}
}