[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
@@ -1,37 +0,0 @@
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();
}
}
@@ -1,58 +0,0 @@
package com.baeldung.jackson.annotation.extra;
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;
}
}
}
@@ -1,133 +0,0 @@
package com.baeldung.jackson.annotation.extra;
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.annotation.extra.AppendBeans.BeanWithAppend;
import com.baeldung.jackson.annotation.extra.AppendBeans.BeanWithoutAppend;
import com.baeldung.jackson.annotation.extra.IdentityReferenceBeans.BeanWithIdentityReference;
import com.baeldung.jackson.annotation.extra.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 ExtraAnnotationUnitTest {
@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));
}
}
@@ -1,62 +0,0 @@
package com.baeldung.jackson.annotation.extra;
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;
}
}
}
@@ -1,31 +0,0 @@
package com.baeldung.jackson.annotation.extra;
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;
}
}
@@ -1,51 +0,0 @@
package com.baeldung.jackson.annotation.extra;
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;
}
}
@@ -1,25 +0,0 @@
package com.baeldung.jackson.annotation.extra;
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;
}
}
@@ -1,30 +0,0 @@
package com.baeldung.jackson.annotation.extra;
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;
}
}
@@ -1,130 +0,0 @@
package com.baeldung.jackson.annotation.extra;
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);
}
}
}
@@ -1,29 +0,0 @@
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>();
}
}
@@ -1,32 +0,0 @@
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);
}
}
@@ -1,17 +0,0 @@
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;
}
}
@@ -1,21 +0,0 @@
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;
}
}
@@ -1,17 +0,0 @@
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;
}
}
@@ -1,21 +0,0 @@
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;
}
}
@@ -1,17 +0,0 @@
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;
}
}
@@ -1,26 +0,0 @@
package com.baeldung.jackson.bidirection;
import com.baeldung.jackson.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;
}
}
@@ -1,24 +0,0 @@
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);
}
}
@@ -1,28 +0,0 @@
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);
}
}
@@ -1,28 +0,0 @@
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);
}
}
@@ -1,28 +0,0 @@
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);
}
}
@@ -1,30 +0,0 @@
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);
}
}
@@ -1,33 +0,0 @@
package com.baeldung.jackson.bidirection;
import java.util.ArrayList;
import java.util.List;
import com.baeldung.jackson.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);
}
}
@@ -1,11 +0,0 @@
package com.baeldung.jackson.exception;
public class User {
public int id;
public String name;
public User(final int id, final String name) {
this.id = id;
this.name = name;
}
}
@@ -1,25 +0,0 @@
package com.baeldung.jackson.exception;
public class UserWithConflict {
public int id;
public String name;
boolean checked;
public UserWithConflict() {
super();
}
public UserWithConflict(final int id, final String name, final boolean checked) {
this.id = id;
this.name = name;
this.checked = checked;
}
public boolean getChecked() {
return checked;
}
public boolean isChecked() {
return checked;
}
}
@@ -1,16 +0,0 @@
package com.baeldung.jackson.exception;
public class UserWithPrivateFields {
int id;
String name;
public UserWithPrivateFields() {
super();
}
public UserWithPrivateFields(final int id, final String name) {
this.id = id;
this.name = name;
}
}
@@ -1,18 +0,0 @@
package com.baeldung.jackson.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;
}
}
@@ -1,22 +0,0 @@
package com.baeldung.jackson.exception;
public class Zoo {
public Animal animal;
public Zoo() {
}
}
abstract class Animal {
public String name;
public Animal() {
}
}
class Cat extends Animal {
public int lives;
public Cat() {
}
}
@@ -1,25 +0,0 @@
package com.baeldung.jackson.exception;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
public class ZooConfigured {
public AnimalConfigured animal;
public ZooConfigured() {
}
}
@JsonDeserialize(as = CatConfigured.class)
abstract class AnimalConfigured {
public String name;
public AnimalConfigured() {
}
}
class CatConfigured extends AnimalConfigured {
public int lives;
public CatConfigured() {
}
}
@@ -1,195 +0,0 @@
package com.baeldung.jackson.exception.test;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.util.List;
import org.junit.Test;
import com.baeldung.jackson.exception.User;
import com.baeldung.jackson.exception.UserWithPrivateFields;
import com.baeldung.jackson.exception.UserWithRoot;
import com.baeldung.jackson.exception.Zoo;
import com.baeldung.jackson.exception.ZooConfigured;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
public class JacksonExceptionsUnitTest {
// JsonMappingException: Can not construct instance of
@Test(expected = JsonMappingException.class)
public void givenAbstractClass_whenDeserializing_thenException() throws IOException {
final String json = "{\"animal\":{\"name\":\"lacy\"}}";
final ObjectMapper mapper = new ObjectMapper();
mapper.reader()
.forType(Zoo.class)
.readValue(json);
}
@Test
public void givenAbstractClassConfigured_whenDeserializing_thenCorrect() throws IOException {
final String json = "{\"animal\":{\"name\":\"lacy\"}}";
final ObjectMapper mapper = new ObjectMapper();
mapper.reader()
.forType(ZooConfigured.class)
.readValue(json);
}
// JsonMappingException: No serializer found for class
@Test(expected = JsonMappingException.class)
public void givenClassWithPrivateFields_whenSerializing_thenException() throws IOException {
final UserWithPrivateFields user = new UserWithPrivateFields(1, "John");
final ObjectMapper mapper = new ObjectMapper();
mapper.writer()
.writeValueAsString(user);
}
@Test
public void givenClassWithPrivateFields_whenConfigureSerializing_thenCorrect() throws IOException {
final UserWithPrivateFields user = new UserWithPrivateFields(1, "John");
final ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
final String result = mapper.writer()
.writeValueAsString(user);
assertThat(result, containsString("John"));
}
// JsonMappingException: No suitable constructor found
@Test(expected = JsonMappingException.class)
public void givenNoDefaultConstructor_whenDeserializing_thenException() throws IOException {
final String json = "{\"id\":1,\"name\":\"John\"}";
final ObjectMapper mapper = new ObjectMapper();
mapper.reader()
.forType(User.class)
.readValue(json);
}
@Test
public void givenDefaultConstructor_whenDeserializing_thenCorrect() throws IOException {
final String json = "{\"id\":1,\"name\":\"John\"}";
final ObjectMapper mapper = new ObjectMapper();
final com.baeldung.jackson.dtos.User user = mapper.reader()
.forType(com.baeldung.jackson.dtos.User.class)
.readValue(json);
assertEquals("John", user.name);
}
// JsonMappingException: Root name does not match expected
@Test(expected = JsonMappingException.class)
public void givenWrappedJsonString_whenDeserializing_thenException() throws IOException {
final String json = "{\"user\":{\"id\":1,\"name\":\"John\"}}";
final ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
mapper.reader()
.forType(com.baeldung.jackson.dtos.User.class)
.readValue(json);
}
@Test
public void givenWrappedJsonStringAndConfigureClass_whenDeserializing_thenCorrect() throws IOException {
final String json = "{\"user\":{\"id\":1,\"name\":\"John\"}}";
final ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
final UserWithRoot user = mapper.reader()
.forType(UserWithRoot.class)
.readValue(json);
assertEquals("John", user.name);
}
// JsonMappingException: Can not deserialize instance of
@Test(expected = JsonMappingException.class)
public void givenJsonOfArray_whenDeserializing_thenException() throws JsonProcessingException, IOException {
final String json = "[{\"id\":1,\"name\":\"John\"},{\"id\":2,\"name\":\"Adam\"}]";
final ObjectMapper mapper = new ObjectMapper();
mapper.reader()
.forType(com.baeldung.jackson.dtos.User.class)
.readValue(json);
}
@Test
public void givenJsonOfArray_whenDeserializing_thenCorrect() throws JsonProcessingException, IOException {
final String json = "[{\"id\":1,\"name\":\"John\"},{\"id\":2,\"name\":\"Adam\"}]";
final ObjectMapper mapper = new ObjectMapper();
final List<com.baeldung.jackson.dtos.User> users = mapper.reader()
.forType(new TypeReference<List<com.baeldung.jackson.dtos.User>>() {
})
.readValue(json);
assertEquals(2, users.size());
}
// UnrecognizedPropertyException
@Test(expected = UnrecognizedPropertyException.class)
public void givenJsonStringWithExtra_whenDeserializing_thenException() throws IOException {
final String json = "{\"id\":1,\"name\":\"John\", \"checked\":true}";
final ObjectMapper mapper = new ObjectMapper();
mapper.reader()
.forType(com.baeldung.jackson.dtos.User.class)
.readValue(json);
}
@Test
public void givenJsonStringWithExtra_whenConfigureDeserializing_thenCorrect() throws IOException {
final String json = "{\"id\":1,\"name\":\"John\", \"checked\":true}";
final ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
final com.baeldung.jackson.dtos.User user = mapper.reader()
.forType(com.baeldung.jackson.dtos.User.class)
.readValue(json);
assertEquals("John", user.name);
}
// JsonParseException: Unexpected character (''' (code 39))
@Test(expected = JsonParseException.class)
public void givenStringWithSingleQuotes_whenDeserializing_thenException() throws JsonProcessingException, IOException {
final String json = "{'id':1,'name':'John'}";
final ObjectMapper mapper = new ObjectMapper();
mapper.reader()
.forType(com.baeldung.jackson.dtos.User.class)
.readValue(json);
}
@Test
public void givenStringWithSingleQuotes_whenConfigureDeserializing_thenCorrect() throws JsonProcessingException, IOException {
final String json = "{'id':1,'name':'John'}";
final JsonFactory factory = new JsonFactory();
factory.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES);
final ObjectMapper mapper = new ObjectMapper(factory);
final com.baeldung.jackson.dtos.User user = mapper.reader()
.forType(com.baeldung.jackson.dtos.User.class)
.readValue(json);
assertEquals("John", user.name);
}
}
@@ -1,37 +0,0 @@
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));
}
}
@@ -1,139 +0,0 @@
package com.baeldung.jackson.test;
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.Item;
import com.baeldung.jackson.bidirection.ItemWithIdentity;
import com.baeldung.jackson.bidirection.ItemWithIgnore;
import com.baeldung.jackson.bidirection.ItemWithRef;
import com.baeldung.jackson.bidirection.ItemWithSerializer;
import com.baeldung.jackson.bidirection.ItemWithView;
import com.baeldung.jackson.bidirection.User;
import com.baeldung.jackson.bidirection.UserWithIdentity;
import com.baeldung.jackson.bidirection.UserWithIgnore;
import com.baeldung.jackson.bidirection.UserWithRef;
import com.baeldung.jackson.bidirection.UserWithSerializer;
import com.baeldung.jackson.bidirection.UserWithView;
import com.baeldung.jackson.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);
}
}