Add logic for JSON to OBJ

This commit is contained in:
YuCheng Hu 2022-03-05 11:15:16 -05:00
parent 0e7de6055c
commit 0a88382aef
67 changed files with 2855 additions and 0 deletions

19
jackson-simple/README.md Normal file
View File

@ -0,0 +1,19 @@
### Jackson Articles that are also part of the e-book
This module contains articles about Jackson that are also part of the Jackson Ebook.
### The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [Jackson Annotation Examples](https://www.baeldung.com/jackson-annotations)
- [Intro to the Jackson ObjectMapper](https://www.baeldung.com/jackson-object-mapper-tutorial)
- [Jackson Ignore Properties on Marshalling](https://www.baeldung.com/jackson-ignore-properties-on-serialization)
- [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)
- [Jackson Unmarshalling JSON with Unknown Properties](https://www.baeldung.com/jackson-deserialize-json-unknown-properties)
### NOTE:
Since this is a module tied to an e-book, it should **not** be moved or used to store the code for any further article.

36
jackson-simple/pom.xml Normal file
View File

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<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-simple</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jackson-simple</name>
<parent>
<groupId>com.ossez</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.2-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<!--jackson for xml -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
<build>
<finalName>jackson-simple</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>

View File

@ -0,0 +1,31 @@
package com.ossez.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

@ -0,0 +1,15 @@
package com.ossez.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

@ -0,0 +1,37 @@
package com.ossez.jackson.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Date;
import com.ossez.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

@ -0,0 +1,18 @@
package com.ossez.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

@ -0,0 +1,31 @@
package com.ossez.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

@ -0,0 +1,20 @@
package com.ossez.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

@ -0,0 +1,18 @@
package com.ossez.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

@ -0,0 +1,31 @@
package com.ossez.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

@ -0,0 +1,33 @@
package com.ossez.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

@ -0,0 +1,19 @@
package com.ossez.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

@ -0,0 +1,19 @@
package com.ossez.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

@ -0,0 +1,34 @@
package com.ossez.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

@ -0,0 +1,34 @@
package com.ossez.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

@ -0,0 +1,56 @@
package com.ossez.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

@ -0,0 +1,21 @@
package com.ossez.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;
}
}

View File

@ -0,0 +1,17 @@
package com.ossez.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;
}
}

View File

@ -0,0 +1,21 @@
package com.ossez.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;
}
}

View File

@ -0,0 +1,28 @@
package com.ossez.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);
}
}

View File

@ -0,0 +1,28 @@
package com.ossez.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);
}
}

View File

@ -0,0 +1,28 @@
package com.ossez.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);
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,41 @@
package com.ossez.jackson.annotation.deserialization;
import java.io.IOException;
import com.ossez.jackson.annotation.dtos.ItemWithSerializer;
import com.ossez.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));
}
}

View File

@ -0,0 +1,32 @@
package com.ossez.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;
}
}

View File

@ -0,0 +1,36 @@
package com.ossez.jackson.annotation.dtos;
import com.ossez.jackson.annotation.deserialization.ItemDeserializerOnClass;
import com.ossez.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;
}
}

View File

@ -0,0 +1,26 @@
package com.ossez.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;
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,8 @@
package com.ossez.jackson.annotation.ignore;
import com.fasterxml.jackson.annotation.JsonIgnoreType;
@JsonIgnoreType
public class MyMixInForIgnoreType {
//
}

View File

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

View File

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

View File

@ -0,0 +1,32 @@
package com.ossez.jackson.annotation.serialization;
import java.io.IOException;
import com.ossez.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();
}
}

View File

@ -0,0 +1,32 @@
package com.ossez.jackson.annotation.serialization;
import java.io.IOException;
import com.ossez.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();
}
}

View File

@ -0,0 +1,54 @@
package com.ossez.jackson.ignore;
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 + "]";
}
}

View File

@ -0,0 +1,42 @@
package com.ossez.jackson.ignore;
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

@ -0,0 +1,42 @@
package com.ossez.jackson.ignore;
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

@ -0,0 +1,51 @@
package com.ossez.jackson.ignore;
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

@ -0,0 +1,43 @@
package com.ossez.jackson.ignore;
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;
}
}

View File

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

View File

@ -0,0 +1,54 @@
package com.ossez.jackson.ignore;
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 + "]";
}
}

View File

@ -0,0 +1,8 @@
package com.ossez.jackson.ignore;
import com.fasterxml.jackson.annotation.JsonIgnoreType;
@JsonIgnoreType
public class MyMixInForIgnoreType {
//
}

View File

@ -0,0 +1,54 @@
package com.ossez.jackson.ignorenullfields;
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 + "]";
}
}

View File

@ -0,0 +1,51 @@
package com.ossez.jackson.ignorenullfields;
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

@ -0,0 +1,54 @@
package com.ossez.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 + "]";
}
}

View File

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

View File

@ -0,0 +1,42 @@
package com.ossez.jackson.objectmapper;
import java.io.IOException;
import com.ossez.jackson.objectmapper.dto.Car;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
public class CustomCarDeserializer extends StdDeserializer<Car> {
private static final long serialVersionUID = -5918629454846356161L;
private final Logger Logger = LoggerFactory.getLogger(getClass());
public CustomCarDeserializer() {
this(null);
}
public CustomCarDeserializer(final Class<?> vc) {
super(vc);
}
@Override
public Car deserialize(final JsonParser parser, final DeserializationContext deserializer) throws IOException {
final Car car = new Car();
final ObjectCodec codec = parser.getCodec();
final JsonNode node = codec.readTree(parser);
try {
final JsonNode colorNode = node.get("color");
final String color = colorNode.asText();
car.setColor(color);
} catch (final Exception e) {
Logger.debug("101_parse_exeption: unknown json.");
}
return car;
}
}

View File

@ -0,0 +1,29 @@
package com.ossez.jackson.objectmapper;
import java.io.IOException;
import com.ossez.jackson.objectmapper.dto.Car;
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 CustomCarSerializer extends StdSerializer<Car> {
private static final long serialVersionUID = 1396140685442227917L;
public CustomCarSerializer() {
this(null);
}
public CustomCarSerializer(final Class<Car> t) {
super(t);
}
@Override
public void serialize(final Car car, final JsonGenerator jsonGenerator, final SerializerProvider serializer) throws IOException, JsonProcessingException {
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("model: ", car.getType());
jsonGenerator.writeEndObject();
}
}

View File

@ -0,0 +1,31 @@
package com.ossez.jackson.objectmapper.dto;
public class Car {
private String color;
private String type;
public Car() {
}
public Car(final String color, final String type) {
this.color = color;
this.type = type;
}
public String getColor() {
return color;
}
public void setColor(final String color) {
this.color = color;
}
public String getType() {
return type;
}
public void setType(final String type) {
this.type = type;
}
}

View File

@ -0,0 +1,24 @@
package com.ossez.jackson.objectmapper.dto;
import java.util.Date;
public class Request {
Car car;
Date datePurchased;
public Car getCar() {
return car;
}
public void setCar(final Car car) {
this.car = car;
}
public Date getDatePurchased() {
return datePurchased;
}
public void setDatePurchased(final Date datePurchased) {
this.datePurchased = datePurchased;
}
}

View File

@ -0,0 +1,54 @@
package com.ossez.jackson.unknownproperties;
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 + "]";
}
}

View File

@ -0,0 +1,50 @@
package com.ossez.jackson.unknownproperties;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyDtoIgnoreType {
private String stringValue;
private int intValue;
private boolean booleanValue;
public MyDtoIgnoreType() {
super();
}
public MyDtoIgnoreType(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

@ -0,0 +1,50 @@
package com.ossez.jackson.unknownproperties;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyDtoIgnoreUnknown {
private String stringValue;
private int intValue;
private boolean booleanValue;
public MyDtoIgnoreUnknown() {
super();
}
public MyDtoIgnoreUnknown(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

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,406 @@
package com.ossez.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 com.ossez.jackson.annotation.bidirection.ItemWithIdentity;
import com.ossez.jackson.annotation.bidirection.ItemWithRef;
import com.ossez.jackson.annotation.bidirection.UserWithIdentity;
import com.ossez.jackson.annotation.bidirection.UserWithRef;
import com.ossez.jackson.annotation.date.EventWithFormat;
import com.ossez.jackson.annotation.date.EventWithSerializer;
import com.ossez.jackson.annotation.dtos.User;
import com.ossez.jackson.annotation.dtos.withEnum.DistanceEnumWithValue;
import com.ossez.jackson.annotation.exception.UserWithRoot;
import com.ossez.jackson.annotation.exception.UserWithRootNamespace;
import com.ossez.jackson.annotation.ignore.MyMixInForIgnoreType;
import com.ossez.jackson.annotation.jsonview.Item;
import com.ossez.jackson.annotation.jsonview.Views;
import org.junit.Test;
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.ossez.jackson.annotation.dtos.Item item = new com.ossez.jackson.annotation.dtos.Item(1, "book", null);
String result = new ObjectMapper().writeValueAsString(item);
assertThat(result, containsString("owner"));
final ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(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

@ -0,0 +1,87 @@
package com.ossez.jackson.ignore;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
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;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
public class IgnoreFieldsWithFilterUnitTest {
@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);
}
}

View File

@ -0,0 +1,111 @@
package com.ossez.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 org.junit.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
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 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);
}
}

View File

@ -0,0 +1,41 @@
package com.ossez.jackson.ignorenullfields;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
public class IgnoreNullFieldsUnitTest {
@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);
}
}

View File

@ -0,0 +1,39 @@
package com.ossez.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 org.junit.Test;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
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);
}
}

View File

@ -0,0 +1,114 @@
package com.ossez.jackson.objectmapper;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.net.URL;
import java.util.List;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import com.ossez.jackson.objectmapper.dto.Car;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JavaReadWriteJsonExampleUnitTest {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
final String EXAMPLE_JSON = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
final String LOCAL_JSON = "[{ \"color\" : \"Black\", \"type\" : \"BMW\" }, { \"color\" : \"Red\", \"type\" : \"BMW\" }]";
@Test
public void whenWriteJavaToJson_thanCorrect() throws Exception {
final ObjectMapper objectMapper = new ObjectMapper();
final Car car = new Car("yellow", "renault");
final String carAsString = objectMapper.writeValueAsString(car);
assertThat(carAsString, containsString("yellow"));
assertThat(carAsString, containsString("renault"));
}
@Test
public void whenWriteToFile_thanCorrect() throws Exception {
File resultFile = folder.newFile("car.json");
ObjectMapper objectMapper = new ObjectMapper();
Car car = new Car("yellow", "renault");
objectMapper.writeValue(resultFile, car);
Car fromFile = objectMapper.readValue(resultFile, Car.class);
assertEquals(car.getType(), fromFile.getType());
assertEquals(car.getColor(), fromFile.getColor());
}
@Test
public void whenReadJsonToJava_thanCorrect() throws Exception {
final ObjectMapper objectMapper = new ObjectMapper();
final Car car = objectMapper.readValue(EXAMPLE_JSON, Car.class);
assertNotNull(car);
assertThat(car.getColor(), containsString("Black"));
}
@Test
public void whenReadJsonToJsonNode_thanCorrect() throws Exception {
final ObjectMapper objectMapper = new ObjectMapper();
final JsonNode jsonNode = objectMapper.readTree(EXAMPLE_JSON);
assertNotNull(jsonNode);
assertThat(jsonNode.get("color")
.asText(), containsString("Black"));
}
@Test
public void whenReadJsonToList_thanCorrect() throws Exception {
final ObjectMapper objectMapper = new ObjectMapper();
final List<Car> listCar = objectMapper.readValue(LOCAL_JSON, new TypeReference<List<Car>>() {
});
for (final Car car : listCar) {
assertNotNull(car);
assertThat(car.getType(), equalTo("BMW"));
}
}
@Test
public void whenReadJsonToMap_thanCorrect() throws Exception {
final ObjectMapper objectMapper = new ObjectMapper();
final Map<String, Object> map = objectMapper.readValue(EXAMPLE_JSON, new TypeReference<Map<String, Object>>() {
});
assertNotNull(map);
for (final String key : map.keySet()) {
assertNotNull(key);
}
}
@Test
public void wheReadFromFile_thanCorrect() throws Exception {
File resource = new File("src/test/resources/json_car.json");
ObjectMapper objectMapper = new ObjectMapper();
Car fromFile = objectMapper.readValue(resource, Car.class);
assertEquals("BMW", fromFile.getType());
assertEquals("Black", fromFile.getColor());
}
@Test
public void wheReadFromUrl_thanCorrect() throws Exception {
URL resource = new URL("file:src/test/resources/json_car.json");
ObjectMapper objectMapper = new ObjectMapper();
Car fromFile = objectMapper.readValue(resource, Car.class);
assertEquals("BMW", fromFile.getType());
assertEquals("Black", fromFile.getColor());
}
}

View File

@ -0,0 +1,85 @@
package com.ossez.jackson.objectmapper;
import com.ossez.jackson.objectmapper.dto.Car;
import com.ossez.jackson.objectmapper.dto.Request;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.junit.Test;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
public class SerializationDeserializationFeatureUnitTest {
final String EXAMPLE_JSON = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
final String JSON_CAR = "{ \"color\" : \"Black\", \"type\" : \"Fiat\", \"year\" : \"1970\" }";
final String JSON_ARRAY = "[{ \"color\" : \"Black\", \"type\" : \"BMW\" }, { \"color\" : \"Red\", \"type\" : \"BMW\" }]";
@Test
public void whenFailOnUnkownPropertiesFalse_thanJsonReadCorrectly() throws Exception {
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
final Car car = objectMapper.readValue(JSON_CAR, Car.class);
final JsonNode jsonNodeRoot = objectMapper.readTree(JSON_CAR);
final JsonNode jsonNodeYear = jsonNodeRoot.get("year");
final String year = jsonNodeYear.asText();
assertNotNull(car);
assertThat(car.getColor(), equalTo("Black"));
assertThat(year, containsString("1970"));
}
@Test
public void whenCustomSerializerDeserializer_thanReadWriteCorrect() throws Exception {
final ObjectMapper mapper = new ObjectMapper();
final SimpleModule serializerModule = new SimpleModule("CustomSerializer", new Version(1, 0, 0, null, null, null));
serializerModule.addSerializer(Car.class, new CustomCarSerializer());
mapper.registerModule(serializerModule);
final Car car = new Car("yellow", "renault");
final String carJson = mapper.writeValueAsString(car);
assertThat(carJson, containsString("renault"));
assertThat(carJson, containsString("model"));
final SimpleModule deserializerModule = new SimpleModule("CustomCarDeserializer", new Version(1, 0, 0, null, null, null));
deserializerModule.addDeserializer(Car.class, new CustomCarDeserializer());
mapper.registerModule(deserializerModule);
final Car carResult = mapper.readValue(EXAMPLE_JSON, Car.class);
assertNotNull(carResult);
assertThat(carResult.getColor(), equalTo("Black"));
}
@Test
public void whenDateFormatSet_thanSerializedAsExpected() throws Exception {
final ObjectMapper objectMapper = new ObjectMapper();
final Car car = new Car("yellow", "renault");
final Request request = new Request();
request.setCar(car);
request.setDatePurchased(new Date());
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm a z");
objectMapper.setDateFormat(df);
final String carAsString = objectMapper.writeValueAsString(request);
assertNotNull(carAsString);
assertThat(carAsString, containsString("datePurchased"));
}
@Test
public void whenUseJavaArrayForJsonArrayTrue_thanJsonReadAsArray() throws Exception {
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
final Car[] cars = objectMapper.readValue(JSON_ARRAY, Car[].class);
for (final Car car : cars) {
assertNotNull(car);
assertThat(car.getType(), equalTo("BMW"));
}
}
}

View File

@ -0,0 +1,80 @@
package com.ossez.jackson.unknownproperties;
import com.fasterxml.jackson.core.JsonParseException;
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;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
public class UnknownPropertiesUnitTest {
@Test
public final void givenNotAllFieldsHaveValuesInJson_whenDeserializingAJsonToAClass_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
final String jsonAsString = "{\"stringValue\":\"a\",\"booleanValue\":true}";
final ObjectMapper mapper = new ObjectMapper();
final MyDto readValue = mapper.readValue(jsonAsString, MyDto.class);
assertNotNull(readValue);
assertThat(readValue.getStringValue(), equalTo("a"));
assertThat(readValue.isBooleanValue(), equalTo(true));
}
// tests - json with unknown fields
@Test(expected = UnrecognizedPropertyException.class)
public final void givenJsonHasUnknownValues_whenDeserializingAJsonToAClass_thenExceptionIsThrown() throws JsonParseException, JsonMappingException, IOException {
final String jsonAsString = "{\"stringValue\":\"a\",\"intValue\":1,\"booleanValue\":true,\"stringValue2\":\"something\"}";
final ObjectMapper mapper = new ObjectMapper();
final MyDto readValue = mapper.readValue(jsonAsString, MyDto.class);
assertNotNull(readValue);
assertThat(readValue.getStringValue(), equalTo("a"));
assertThat(readValue.isBooleanValue(), equalTo(true));
assertThat(readValue.getIntValue(), equalTo(1));
}
@Test
public final void givenJsonHasUnknownValuesButJacksonIsIgnoringUnknownFields_whenDeserializing_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
final String jsonAsString = // @formatter:off
"{\"stringValue\":\"a\"," +
"\"intValue\":1," +
"\"booleanValue\":true," +
"\"stringValue2\":\"something\"}"; // @formatter:on
final ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
final MyDto readValue = mapper.readValue(jsonAsString, MyDto.class);
assertNotNull(readValue);
assertThat(readValue.getStringValue(), equalTo("a"));
assertThat(readValue.isBooleanValue(), equalTo(true));
assertThat(readValue.getIntValue(), equalTo(1));
}
@Test
public final void givenJsonHasUnknownValuesButUnknownFieldsAreIgnoredOnClass_whenDeserializing_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
final String jsonAsString = // @formatter:off
"{\"stringValue\":\"a\"," +
"\"intValue\":1," +
"\"booleanValue\":true," +
"\"stringValue2\":\"something\"}"; // @formatter:on
final ObjectMapper mapper = new ObjectMapper();
final MyDtoIgnoreUnknown readValue = mapper.readValue(jsonAsString, MyDtoIgnoreUnknown.class);
assertNotNull(readValue);
assertThat(readValue.getStringValue(), equalTo("a"));
assertThat(readValue.isBooleanValue(), equalTo(true));
assertThat(readValue.getIntValue(), equalTo(1));
}
}

View File

@ -0,0 +1,4 @@
{
"color": "Black",
"type": "BMW"
}