[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 16de535f00
commit 5cc2d3dc07
97 changed files with 894 additions and 210 deletions

View File

@@ -7,9 +7,6 @@ This module contains articles about Jackson that are also part of the Jackson Eb
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [Jackson Ignore Properties on Marshalling](https://www.baeldung.com/jackson-ignore-properties-on-serialization)
- [Jackson Unmarshalling json with Unknown Properties](https://www.baeldung.com/jackson-deserialize-json-unknown-properties)
- [Jackson Annotation Examples](https://www.baeldung.com/jackson-annotations)
- [Intro to the Jackson ObjectMapper](https://www.baeldung.com/jackson-object-mapper-tutorial)
- [Ignore Null Fields with Jackson](https://www.baeldung.com/jackson-ignore-null-fields)
- [Jackson Change Name of Field](https://www.baeldung.com/jackson-name-of-property)

View File

@@ -1,31 +0,0 @@
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;
}
}

View File

@@ -1,15 +0,0 @@
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;
}
}

View File

@@ -1,37 +0,0 @@
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 {
}
}

View File

@@ -1,18 +0,0 @@
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;
}
}

View File

@@ -1,31 +0,0 @@
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;
}
}

View File

@@ -1,20 +0,0 @@
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;
}
}

View File

@@ -1,18 +0,0 @@
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;
}
}

View File

@@ -1,31 +0,0 @@
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;
}
}

View File

@@ -1,33 +0,0 @@
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;
}
}

View File

@@ -1,19 +0,0 @@
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;
}
}

View File

@@ -1,19 +0,0 @@
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;
}
}

View File

@@ -1,34 +0,0 @@
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;
}
}
}

View File

@@ -1,34 +0,0 @@
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;
}
}
}

View File

@@ -1,56 +0,0 @@
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;
}
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -1,36 +0,0 @@
package com.baeldung.jackson.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);
}
}
}

View File

@@ -1,29 +0,0 @@
package com.baeldung.jackson.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));
}
}

View File

@@ -1,29 +0,0 @@
package com.baeldung.jackson.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;
}
}

View File

@@ -1,31 +0,0 @@
package com.baeldung.jackson.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;
}
}

View File

@@ -1,50 +0,0 @@
package com.baeldung.jackson.dtos;
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;
}
}

View File

@@ -1,21 +0,0 @@
package com.baeldung.jackson.dtos;
public class MyDtoNoAccessors {
String stringValue;
int intValue;
boolean booleanValue;
public MyDtoNoAccessors() {
super();
}
public MyDtoNoAccessors(final String stringValue, final int intValue, final boolean booleanValue) {
super();
this.stringValue = stringValue;
this.intValue = intValue;
this.booleanValue = booleanValue;
}
}

View File

@@ -1,25 +0,0 @@
package com.baeldung.jackson.dtos;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
public class MyDtoNoAccessorsAndFieldVisibility {
String stringValue;
int intValue;
boolean booleanValue;
public MyDtoNoAccessorsAndFieldVisibility() {
super();
}
public MyDtoNoAccessorsAndFieldVisibility(final String stringValue, final int intValue, final boolean booleanValue) {
super();
this.stringValue = stringValue;
this.intValue = intValue;
this.booleanValue = booleanValue;
}
}

View File

@@ -1,4 +1,4 @@
package com.baeldung.jackson.dtos.withEnum;
package com.baeldung.jackson.annotation.dtos.withEnum;
import com.fasterxml.jackson.annotation.JsonValue;

View File

@@ -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;
}
}

View File

@@ -1,18 +0,0 @@
package com.baeldung.jackson.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;
}
}

View File

@@ -1,278 +0,0 @@
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.dtos.MyDto;
import com.baeldung.jackson.dtos.MyDtoIncludeNonDefault;
import com.baeldung.jackson.dtos.MyDtoWithFilter;
import com.baeldung.jackson.dtos.MyDtoWithSpecialField;
import com.baeldung.jackson.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.serialization.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);
}
}

View File

@@ -1,42 +0,0 @@
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;
}
}

View File

@@ -1,42 +0,0 @@
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;
}
}

View File

@@ -1,51 +0,0 @@
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;
}
}

View File

@@ -1,36 +0,0 @@
package com.baeldung.jackson.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;
}
}

View File

@@ -1,9 +0,0 @@
package com.baeldung.jackson.jsonview;
public class Views {
public static class Public {
}
public static class Internal extends Public {
}
}

View File

@@ -1,27 +0,0 @@
package com.baeldung.jackson.serialization;
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("");
}
}

View File

@@ -1,419 +0,0 @@
package com.baeldung.jackson.test;
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.AliasBean;
import com.baeldung.jackson.annotation.BeanWithCreator;
import com.baeldung.jackson.annotation.BeanWithCustomAnnotation;
import com.baeldung.jackson.annotation.BeanWithFilter;
import com.baeldung.jackson.annotation.BeanWithGetter;
import com.baeldung.jackson.annotation.BeanWithIgnore;
import com.baeldung.jackson.annotation.BeanWithInject;
import com.baeldung.jackson.annotation.ExtendableBean;
import com.baeldung.jackson.annotation.MyBean;
import com.baeldung.jackson.annotation.PrivateBean;
import com.baeldung.jackson.annotation.RawBean;
import com.baeldung.jackson.annotation.UnwrappedUser;
import com.baeldung.jackson.annotation.UserWithIgnoreType;
import com.baeldung.jackson.annotation.Zoo;
import com.baeldung.jackson.bidirection.ItemWithIdentity;
import com.baeldung.jackson.bidirection.ItemWithRef;
import com.baeldung.jackson.bidirection.UserWithIdentity;
import com.baeldung.jackson.bidirection.UserWithRef;
import com.baeldung.jackson.date.EventWithFormat;
import com.baeldung.jackson.date.EventWithSerializer;
import com.baeldung.jackson.dtos.MyMixInForIgnoreType;
import com.baeldung.jackson.dtos.withEnum.DistanceEnumWithValue;
import com.baeldung.jackson.exception.UserWithRoot;
import com.baeldung.jackson.exception.UserWithRootNamespace;
import com.baeldung.jackson.jsonview.Item;
import com.baeldung.jackson.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.dtos.Item item = new com.baeldung.jackson.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.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>
*/
}
}

View File

@@ -8,13 +8,10 @@ import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.util.List;
import com.baeldung.jackson.dtos.MyDtoFieldNameChanged;
import com.baeldung.jackson.dtos.User;
import com.baeldung.jackson.dtos.Item;
import com.baeldung.jackson.dtos.ItemWithSerializer;
import com.baeldung.jackson.dtos.MyDto;
import com.baeldung.jackson.dtos.MyDtoNoAccessors;
import com.baeldung.jackson.dtos.MyDtoNoAccessorsAndFieldVisibility;
import com.baeldung.jackson.serialization.ItemSerializer;
import org.junit.Test;
@@ -29,61 +26,6 @@ import com.google.common.collect.Lists;
public class JacksonSerializationUnitTest {
// tests - single entity to json
@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);
}
// tests - serialize via accessors/fields
@Test(expected = JsonMappingException.class)
public final void givenObjectHasNoAccessors_whenSerializing_thenException() throws JsonParseException, IOException {
final String dtoAsString = new ObjectMapper().writeValueAsString(new MyDtoNoAccessors());
assertThat(dtoAsString, notNullValue());
}
@Test
public final void givenObjectHasNoAccessors_whenSerializingWithPrivateFieldsVisibility_thenNoException() throws JsonParseException, IOException {
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
final String dtoAsString = objectMapper.writeValueAsString(new MyDtoNoAccessors());
assertThat(dtoAsString, containsString("intValue"));
assertThat(dtoAsString, containsString("stringValue"));
assertThat(dtoAsString, containsString("booleanValue"));
}
@Test
public final void givenObjectHasNoAccessorsButHasVisibleFields_whenSerializing_thenNoException() throws JsonParseException, IOException {
final ObjectMapper objectMapper = new ObjectMapper();
final String dtoAsString = objectMapper.writeValueAsString(new MyDtoNoAccessorsAndFieldVisibility());
assertThat(dtoAsString, containsString("intValue"));
assertThat(dtoAsString, containsString("stringValue"));
assertThat(dtoAsString, containsString("booleanValue"));
}
// tests - multiple entities to json
@Test