Compare commits

..

2 Commits

74 changed files with 62 additions and 2627 deletions

View File

@ -13,6 +13,7 @@
<module name="core-java-annotations" />
<module name="core-java-uuid" />
<module name="core-java-numbers" />
<module name="jackson-polymorphic-deserialization" />
<module name="core-java-strings" />
<module name="jackson" />
<module name="core-java-11" />

View File

@ -75,6 +75,8 @@
<file url="file://$PROJECT_DIR$/jackson-modules/jackson-exceptions/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jackson-modules/jackson-jr/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jackson-modules/jackson-jr/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jackson-modules/jackson-polymorphic-deserialization/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jackson-modules/jackson-polymorphic-deserialization/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jackson-modules/jackson/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jackson-modules/jackson/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/jackson-modules/src/main/java" charset="UTF-8" />

View File

@ -1,20 +0,0 @@
## Jackson Cookbooks and Examples
This module contains articles about Jackson.
### The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [Using Optional with Jackson](https://www.baeldung.com/jackson-optional)
- [Compare Two JSON Objects with Jackson](https://www.baeldung.com/jackson-compare-two-json-objects)
- [Jackson vs Gson](https://www.baeldung.com/jackson-vs-gson)
- [Inheritance with Jackson](https://www.baeldung.com/jackson-inheritance)
- [Working with Tree Model Nodes in Jackson](https://www.baeldung.com/jackson-json-node-tree-model)
- [Get all the Keys in a JSON String Using JsonNode](https://www.baeldung.com/java-jsonnode-get-keys)
- [Difference Between asText() and toString() in JsonNode](https://www.baeldung.com/java-jsonnode-astext-vs-tostring)
- [Deserialize Generic Type with Jackson](https://www.baeldung.com/java-deserialize-generic-type-with-jackson)
- [Setting Default Values to Null Fields in Jackson Mapping](https://www.baeldung.com/java-jackson-mapping-default-values-null-fields)
- [Removing JSON Elements With Jackson](https://www.baeldung.com/java-jackson-remove-json-elements)

View File

@ -1,67 +0,0 @@
<?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-core</artifactId>
<name>jackson-core</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>jackson-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<!-- marshalling -->
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jsonSchema</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>${rest-assured.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-path</artifactId>
<version>${rest-assured.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>jackson-core</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<!-- testing -->
<rest-assured.version>5.4.0</rest-assured.version>
</properties>
</project>

View File

@ -1,43 +0,0 @@
package com.baeldung.jackson.deserialization.jacksoninject;
import com.fasterxml.jackson.annotation.JacksonInject;
import java.util.UUID;
public class Person {
@JacksonInject
private UUID id;
private String firstName;
private String lastName;
public Person() {
}
public Person(String firstName, String lastName) {
this.id = UUID.randomUUID();
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public UUID getId() {
return id;
}
}

View File

@ -1,20 +0,0 @@
package com.baeldung.jackson.deserialization.jsonanysetter;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnySetter;
public class Inventory {
private Map<String, Float> countryDeliveryCost = new HashMap<>();
public Map<String, Float> getCountryDeliveryCost() {
return countryDeliveryCost;
}
@JsonAnySetter
public void addCountryDeliveryCost(String country, Float cost) {
countryDeliveryCost.put(country, cost);
}
}

View File

@ -1,75 +0,0 @@
package com.baeldung.jackson.deserialization.jsondeserialize;
import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
public class Book {
private UUID id;
private String title;
private float price;
private String ISBN;
@JsonDeserialize(using = CustomDateDeserializer.class)
private Date published;
private BigDecimal pages;
public Book() {
}
public Book(String title) {
this.id = UUID.randomUUID();
this.title = title;
}
public String getISBN() {
return ISBN;
}
public void setISBN(String ISBN) {
this.ISBN = ISBN;
}
public Date getPublished() {
return published;
}
public void setPublished(Date published) {
this.published = published;
}
public BigDecimal getPages() {
return pages;
}
public void setPages(BigDecimal pages) {
this.pages = pages;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}

View File

@ -1,33 +0,0 @@
package com.baeldung.jackson.deserialization.jsondeserialize;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CustomDateDeserializer extends StdDeserializer<Date> {
private static SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
public CustomDateDeserializer() {
this(null);
}
public CustomDateDeserializer(Class<?> vc) {
super(vc);
}
@Override
public Date deserialize(JsonParser jsonparser, DeserializationContext context) throws IOException {
String date = jsonparser.getText();
try {
return formatter.parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -1,30 +0,0 @@
package com.baeldung.jackson.domain;
public class Person {
private String firstName;
private String lastName;
public Person(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}

View File

@ -1,25 +0,0 @@
package com.baeldung.jackson.inheritance;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonTypeInfo(use = JsonTypeInfo.Id.MINIMAL_CLASS, include = JsonTypeInfo.As.PROPERTY, property = "eventType")
abstract public class Event {
private final String id;
private final Long timestamp;
@JsonCreator
public Event(@JsonProperty("id") String id, @JsonProperty("timestamp") Long timestamp) {
this.id = id;
this.timestamp = timestamp;
}
public Long getTimestamp() {
return timestamp;
}
public String getId() {
return id;
}
}

View File

@ -1,96 +0,0 @@
package com.baeldung.jackson.inheritance;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
public class IgnoranceAnnotationStructure {
public static abstract class Vehicle {
private String make;
private String model;
protected Vehicle() {
}
protected Vehicle(String make, String model) {
this.make = make;
this.model = model;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
@JsonIgnoreProperties({ "model", "seatingCapacity" })
public static abstract class Car extends Vehicle {
private int seatingCapacity;
@JsonIgnore
private double topSpeed;
protected Car() {
}
protected Car(String make, String model, int seatingCapacity, double topSpeed) {
super(make, model);
this.seatingCapacity = seatingCapacity;
this.topSpeed = topSpeed;
}
public int getSeatingCapacity() {
return seatingCapacity;
}
public void setSeatingCapacity(int seatingCapacity) {
this.seatingCapacity = seatingCapacity;
}
public double getTopSpeed() {
return topSpeed;
}
public void setTopSpeed(double topSpeed) {
this.topSpeed = topSpeed;
}
}
public static class Sedan extends Car {
public Sedan() {
}
public Sedan(String make, String model, int seatingCapacity, double topSpeed) {
super(make, model, seatingCapacity, topSpeed);
}
}
public static class Crossover extends Car {
private double towingCapacity;
public Crossover() {
}
public Crossover(String make, String model, int seatingCapacity, double topSpeed, double towingCapacity) {
super(make, model, seatingCapacity, topSpeed);
this.towingCapacity = towingCapacity;
}
public double getTowingCapacity() {
return towingCapacity;
}
public void setTowingCapacity(double towingCapacity) {
this.towingCapacity = towingCapacity;
}
}
}

View File

@ -1,91 +0,0 @@
package com.baeldung.jackson.inheritance;
public class IgnoranceMixinOrIntrospection {
public static abstract class Vehicle {
private String make;
private String model;
protected Vehicle() {
}
protected Vehicle(String make, String model) {
this.make = make;
this.model = model;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
public static abstract class Car extends Vehicle {
private int seatingCapacity;
private double topSpeed;
protected Car() {
}
protected Car(String make, String model, int seatingCapacity, double topSpeed) {
super(make, model);
this.seatingCapacity = seatingCapacity;
this.topSpeed = topSpeed;
}
public int getSeatingCapacity() {
return seatingCapacity;
}
public void setSeatingCapacity(int seatingCapacity) {
this.seatingCapacity = seatingCapacity;
}
public double getTopSpeed() {
return topSpeed;
}
public void setTopSpeed(double topSpeed) {
this.topSpeed = topSpeed;
}
}
public static class Sedan extends Car {
public Sedan() {
}
public Sedan(String make, String model, int seatingCapacity, double topSpeed) {
super(make, model, seatingCapacity, topSpeed);
}
}
public static class Crossover extends Car {
private double towingCapacity;
public Crossover() {
}
public Crossover(String make, String model, int seatingCapacity, double topSpeed, double towingCapacity) {
super(make, model, seatingCapacity, topSpeed);
this.towingCapacity = towingCapacity;
}
public double getTowingCapacity() {
return towingCapacity;
}
public void setTowingCapacity(double towingCapacity) {
this.towingCapacity = towingCapacity;
}
}
}

View File

@ -1,28 +0,0 @@
package com.baeldung.jackson.inheritance;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
@JsonTypeName("itemIdAddedToUser")
@JsonIgnoreProperties("id")
public class ItemIdAddedToUser extends Event {
private final String itemId;
private final Long quantity;
@JsonCreator
public ItemIdAddedToUser(@JsonProperty("id") String id, @JsonProperty("timestamp") Long timestamp, @JsonProperty("itemId") String itemId, @JsonProperty("quantity") Long quantity) {
super(id, timestamp);
this.itemId = itemId;
this.quantity = quantity;
}
public String getItemId() {
return itemId;
}
public Long getQuantity() {
return quantity;
}
}

View File

@ -1,26 +0,0 @@
package com.baeldung.jackson.inheritance;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
@JsonTypeName("itemIdRemovedFromUser")
public class ItemIdRemovedFromUser extends Event {
private final String itemId;
private final Long quantity;
@JsonCreator
public ItemIdRemovedFromUser(@JsonProperty("id") String id, @JsonProperty("timestamp") Long timestamp, @JsonProperty("itemId") String itemId, @JsonProperty("quantity") Long quantity) {
super(id, timestamp);
this.itemId = itemId;
this.quantity = quantity;
}
public String getItemId() {
return itemId;
}
public Long getQuantity() {
return quantity;
}
}

View File

@ -1,92 +0,0 @@
package com.baeldung.jackson.inheritance;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class SubTypeConstructorStructure {
public static class Fleet {
private List<Vehicle> vehicles;
public List<Vehicle> getVehicles() {
return vehicles;
}
public void setVehicles(List<Vehicle> vehicles) {
this.vehicles = vehicles;
}
}
public static abstract class Vehicle {
private String make;
private String model;
protected Vehicle(String make, String model) {
this.make = make;
this.model = model;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
public static class Car extends Vehicle {
private int seatingCapacity;
private double topSpeed;
@JsonCreator
public Car(@JsonProperty("make") String make, @JsonProperty("model") String model, @JsonProperty("seating") int seatingCapacity, @JsonProperty("topSpeed") double topSpeed) {
super(make, model);
this.seatingCapacity = seatingCapacity;
this.topSpeed = topSpeed;
}
public int getSeatingCapacity() {
return seatingCapacity;
}
public void setSeatingCapacity(int seatingCapacity) {
this.seatingCapacity = seatingCapacity;
}
public double getTopSpeed() {
return topSpeed;
}
public void setTopSpeed(double topSpeed) {
this.topSpeed = topSpeed;
}
}
public static class Truck extends Vehicle {
private double payloadCapacity;
@JsonCreator
public Truck(@JsonProperty("make") String make, @JsonProperty("model") String model, @JsonProperty("payload") double payloadCapacity) {
super(make, model);
this.payloadCapacity = payloadCapacity;
}
public double getPayloadCapacity() {
return payloadCapacity;
}
public void setPayloadCapacity(double payloadCapacity) {
this.payloadCapacity = payloadCapacity;
}
}
}

View File

@ -1,87 +0,0 @@
package com.baeldung.jackson.inheritance;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class SubTypeConversionStructure {
public static abstract class Vehicle {
private String make;
private String model;
protected Vehicle() {
}
protected Vehicle(String make, String model) {
this.make = make;
this.model = model;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
public static class Car extends Vehicle {
@JsonIgnore
private int seatingCapacity;
@JsonIgnore
private double topSpeed;
public Car() {
}
public Car(String make, String model, int seatingCapacity, double topSpeed) {
super(make, model);
this.seatingCapacity = seatingCapacity;
this.topSpeed = topSpeed;
}
public int getSeatingCapacity() {
return seatingCapacity;
}
public void setSeatingCapacity(int seatingCapacity) {
this.seatingCapacity = seatingCapacity;
}
public double getTopSpeed() {
return topSpeed;
}
public void setTopSpeed(double topSpeed) {
this.topSpeed = topSpeed;
}
}
public static class Truck extends Vehicle {
@JsonIgnore
private double payloadCapacity;
public Truck() {
}
public Truck(String make, String model, double payloadCapacity) {
super(make, model);
this.payloadCapacity = payloadCapacity;
}
public double getPayloadCapacity() {
return payloadCapacity;
}
public void setPayloadCapacity(double payloadCapacity) {
this.payloadCapacity = payloadCapacity;
}
}
}

View File

@ -1,102 +0,0 @@
package com.baeldung.jackson.inheritance;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
public class TypeInfoAnnotatedStructure {
public static class Fleet {
private List<Vehicle> vehicles;
public List<Vehicle> getVehicles() {
return vehicles;
}
public void setVehicles(List<Vehicle> vehicles) {
this.vehicles = vehicles;
}
}
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({ @Type(value = Car.class, name = "car"), @Type(value = Truck.class, name = "truck") })
public static abstract class Vehicle {
private String make;
private String model;
protected Vehicle() {
}
protected Vehicle(String make, String model) {
this.make = make;
this.model = model;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
public static class Car extends Vehicle {
private int seatingCapacity;
private double topSpeed;
public Car() {
}
public Car(String make, String model, int seatingCapacity, double topSpeed) {
super(make, model);
this.seatingCapacity = seatingCapacity;
this.topSpeed = topSpeed;
}
public int getSeatingCapacity() {
return seatingCapacity;
}
public void setSeatingCapacity(int seatingCapacity) {
this.seatingCapacity = seatingCapacity;
}
public double getTopSpeed() {
return topSpeed;
}
public void setTopSpeed(double topSpeed) {
this.topSpeed = topSpeed;
}
}
public static class Truck extends Vehicle {
private double payloadCapacity;
public Truck() {
}
public Truck(String make, String model, double payloadCapacity) {
super(make, model);
this.payloadCapacity = payloadCapacity;
}
public double getPayloadCapacity() {
return payloadCapacity;
}
public void setPayloadCapacity(double payloadCapacity) {
this.payloadCapacity = payloadCapacity;
}
}
}

View File

@ -1,96 +0,0 @@
package com.baeldung.jackson.inheritance;
import java.util.List;
public class TypeInfoStructure {
public static class Fleet {
private List<Vehicle> vehicles;
public List<Vehicle> getVehicles() {
return vehicles;
}
public void setVehicles(List<Vehicle> vehicles) {
this.vehicles = vehicles;
}
}
public static abstract class Vehicle {
private String make;
private String model;
protected Vehicle() {
}
protected Vehicle(String make, String model) {
this.make = make;
this.model = model;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
public static class Car extends Vehicle {
private int seatingCapacity;
private double topSpeed;
public Car() {
}
public Car(String make, String model, int seatingCapacity, double topSpeed) {
super(make, model);
this.seatingCapacity = seatingCapacity;
this.topSpeed = topSpeed;
}
public int getSeatingCapacity() {
return seatingCapacity;
}
public void setSeatingCapacity(int seatingCapacity) {
this.seatingCapacity = seatingCapacity;
}
public double getTopSpeed() {
return topSpeed;
}
public void setTopSpeed(double topSpeed) {
this.topSpeed = topSpeed;
}
}
public static class Truck extends Vehicle {
private double payloadCapacity;
public Truck() {
}
public Truck(String make, String model, double payloadCapacity) {
super(make, model);
this.payloadCapacity = payloadCapacity;
}
public double getPayloadCapacity() {
return payloadCapacity;
}
public void setPayloadCapacity(double payloadCapacity) {
this.payloadCapacity = payloadCapacity;
}
}
}

View File

@ -1,61 +0,0 @@
package com.baeldung.jackson.jacksonvsgson;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
public class ActorJackson {
private String imdbId;
private Date dateOfBirth;
private List<String> filmography;
public ActorJackson() {
super();
}
public ActorJackson(String imdbId, Date dateOfBirth, List<String> filmography) {
super();
this.imdbId = imdbId;
this.dateOfBirth = dateOfBirth;
this.filmography = filmography;
}
@Override
public String toString() {
return "ActorJackson [imdbId=" + imdbId + ", dateOfBirth=" + formatDateOfBirth() + ", filmography=" + filmography + "]";
}
public String getImdbId() {
return imdbId;
}
public void setImdbId(String imdbId) {
this.imdbId = imdbId;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public List<String> getFilmography() {
return filmography;
}
public void setFilmography(List<String> filmography) {
this.filmography = filmography;
}
private String formatDateOfBirth() {
final DateFormat formatter = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy", Locale.US);
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
return formatter.format(dateOfBirth);
}
}

View File

@ -1,32 +0,0 @@
package com.baeldung.jackson.jacksonvsgson;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.stream.Collectors;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
public class ActorJacksonSerializer extends StdSerializer<ActorJackson> {
private SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
public ActorJacksonSerializer(Class t) {
super(t);
}
@Override
public void serialize(ActorJackson actor, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("imdbId", actor.getImdbId());
jsonGenerator.writeObjectField("dateOfBirth", actor.getDateOfBirth() != null ? sdf.format(actor.getDateOfBirth()) : null);
jsonGenerator.writeNumberField("N° Film: ", actor.getFilmography() != null ? actor.getFilmography()
.size() : null);
jsonGenerator.writeStringField("filmography", actor.getFilmography()
.stream()
.collect(Collectors.joining("-")));
jsonGenerator.writeEndObject();
}
}

View File

@ -1,50 +0,0 @@
package com.baeldung.jackson.jacksonvsgson;
import java.util.List;
public class Movie {
private String imdbId;
private String director;
private List<ActorJackson> actors;
public Movie(String imdbId, String director, List<ActorJackson> actors) {
super();
this.imdbId = imdbId;
this.director = director;
this.actors = actors;
}
public Movie() {
super();
}
@Override
public String toString() {
return "Movie [imdbId=" + imdbId + ", director=" + director + ", actors=" + actors + "]";
}
public String getImdbId() {
return imdbId;
}
public void setImdbId(String imdbId) {
this.imdbId = imdbId;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public List<ActorJackson> getActors() {
return actors;
}
public void setActors(List<ActorJackson> actors) {
this.actors = actors;
}
}

View File

@ -1,46 +0,0 @@
package com.baeldung.jackson.jacksonvsgson;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.List;
public class MovieWithNullValue {
private String imdbId;
@JsonIgnore
private String director;
private List<ActorJackson> actors;
public MovieWithNullValue(String imdbID, String director, List<ActorJackson> actors) {
super();
this.imdbId = imdbID;
this.director = director;
this.actors = actors;
}
public String getImdbID() {
return imdbId;
}
public void setImdbID(String imdbID) {
this.imdbId = imdbID;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public List<ActorJackson> getActors() {
return actors;
}
public void setActors(List<ActorJackson> actors) {
this.actors = actors;
}
}

View File

@ -1,62 +0,0 @@
package com.baeldung.jackson.node;
import java.util.Iterator;
import java.util.Map.Entry;
import com.fasterxml.jackson.databind.JsonNode;
public class JsonNodeIterator {
private static final String NEW_LINE = "\n";
private static final String FIELD_DELIMITER = ": ";
private static final String ARRAY_PREFIX = "- ";
private static final String YAML_PREFIX = " ";
public String toYaml(JsonNode root) {
StringBuilder yaml = new StringBuilder();
processNode(root, yaml, 0);
return yaml.toString();
}
private void processNode(JsonNode jsonNode, StringBuilder yaml, int depth) {
if (jsonNode.isValueNode()) {
yaml.append(jsonNode.asText());
}
else if (jsonNode.isArray()) {
for (JsonNode arrayItem : jsonNode) {
appendNodeToYaml(arrayItem, yaml, depth, true);
}
}
else if (jsonNode.isObject()) {
appendNodeToYaml(jsonNode, yaml, depth, false);
}
}
private void appendNodeToYaml(JsonNode node, StringBuilder yaml, int depth, boolean isArrayItem) {
Iterator<Entry<String, JsonNode>> fields = node.fields();
boolean isFirst = true;
while (fields.hasNext()) {
Entry<String, JsonNode> jsonField = fields.next();
addFieldNameToYaml(yaml, jsonField.getKey(), depth, isArrayItem && isFirst);
processNode(jsonField.getValue(), yaml, depth+1);
isFirst = false;
}
}
private void addFieldNameToYaml(StringBuilder yaml, String fieldName, int depth, boolean isFirstInArray) {
if (yaml.length()>0) {
yaml.append(NEW_LINE);
int requiredDepth = (isFirstInArray) ? depth-1 : depth;
for(int i = 0; i < requiredDepth; i++) {
yaml.append(YAML_PREFIX);
}
if (isFirstInArray) {
yaml.append(ARRAY_PREFIX);
}
}
yaml.append(fieldName);
yaml.append(FIELD_DELIMITER);
}
}

View File

@ -1,25 +0,0 @@
package com.baeldung.jackson.optionalwithjackson;
import java.util.Optional;
public class Book {
private String title;
private Optional<String> subTitle;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Optional<String> getSubTitle() {
return subTitle;
}
public void setSubTitle(Optional<String> subTitle) {
this.subTitle = subTitle;
}
}

View File

@ -1,12 +0,0 @@
{
"collection": [
{
"name": "Test order1",
"detail": "ahk ks"
},
{
"name": "Test order2",
"detail": "Fisteku"
}
]
}

View File

@ -1,10 +0,0 @@
[
{
"name": "Test order1",
"detail": "ahk ks"
},
{
"name": "Test order2",
"detail": "Fisteku"
}
]

View File

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

@ -1,33 +0,0 @@
package com.baeldung.jackson.dtos;
public class Address {
String streetNumber;
String streetName;
String city;
public String getStreetNumber() {
return streetNumber;
}
public void setStreetNumber(String streetNumber) {
this.streetNumber = streetNumber;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}

View File

@ -1,54 +0,0 @@
package com.baeldung.jackson.dtos;
public class MyDto {
private String stringValue;
private int intValue;
private boolean booleanValue;
public MyDto() {
super();
}
public MyDto(final String stringValue, final int intValue, final boolean booleanValue) {
super();
this.stringValue = stringValue;
this.intValue = intValue;
this.booleanValue = booleanValue;
}
// API
public String getStringValue() {
return stringValue;
}
public void setStringValue(final String stringValue) {
this.stringValue = stringValue;
}
public int getIntValue() {
return intValue;
}
public void setIntValue(final int intValue) {
this.intValue = intValue;
}
public boolean isBooleanValue() {
return booleanValue;
}
public void setBooleanValue(final boolean booleanValue) {
this.booleanValue = booleanValue;
}
//
@Override
public String toString() {
return "MyDto [stringValue=" + stringValue + ", intValue=" + intValue + ", booleanValue=" + booleanValue + "]";
}
}

View File

@ -1,47 +0,0 @@
package com.baeldung.jackson.dtos;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
@JacksonXmlRootElement(localName = "person")
public final class Person {
private String firstName;
private String lastName;
private List<String> phoneNumbers = new ArrayList<>();
private List<Address> address = new ArrayList<>();
public List<Address> getAddress() {
return address;
}
public void setAddress(List<Address> address) {
this.address = address;
}
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;
}
public List<String> getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(List<String> phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
}

View File

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

@ -1,92 +0,0 @@
package com.baeldung.jackson.inheritance;
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.not;
import org.junit.Test;
import java.util.List;
import java.util.ArrayList;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.introspect.AnnotatedMember;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
public class IgnoranceUnitTest {
private static abstract class CarMixIn {
@JsonIgnore
public String make;
@JsonIgnore
public String topSpeed;
}
private static class IgnoranceIntrospector extends JacksonAnnotationIntrospector {
private static final long serialVersionUID = 1422295680188892323L;
public boolean hasIgnoreMarker(AnnotatedMember m) {
return m.getDeclaringClass() == IgnoranceMixinOrIntrospection.Vehicle.class && m.getName() == "model" || m.getDeclaringClass() == IgnoranceMixinOrIntrospection.Car.class || m.getName() == "towingCapacity" || super.hasIgnoreMarker(m);
}
}
@Test
public void givenAnnotations_whenIgnoringProperties_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
IgnoranceAnnotationStructure.Sedan sedan = new IgnoranceAnnotationStructure.Sedan("Mercedes-Benz", "S500", 5, 250.0);
IgnoranceAnnotationStructure.Crossover crossover = new IgnoranceAnnotationStructure.Crossover("BMW", "X6", 5, 250.0, 6000.0);
List<IgnoranceAnnotationStructure.Vehicle> vehicles = new ArrayList<>();
vehicles.add(sedan);
vehicles.add(crossover);
String jsonDataString = mapper.writeValueAsString(vehicles);
assertThat(jsonDataString, containsString("make"));
assertThat(jsonDataString, not(containsString("model")));
assertThat(jsonDataString, not(containsString("seatingCapacity")));
assertThat(jsonDataString, not(containsString("topSpeed")));
assertThat(jsonDataString, containsString("towingCapacity"));
}
@Test
public void givenMixIns_whenIgnoringProperties_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(IgnoranceMixinOrIntrospection.Car.class, CarMixIn.class);
String jsonDataString = instantiateAndSerializeObjects(mapper);
assertThat(jsonDataString, not(containsString("make")));
assertThat(jsonDataString, containsString("model"));
assertThat(jsonDataString, containsString("seatingCapacity"));
assertThat(jsonDataString, not(containsString("topSpeed")));
assertThat(jsonDataString, containsString("towingCapacity"));
}
@Test
public void givenIntrospection_whenIgnoringProperties_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
mapper.setAnnotationIntrospector(new IgnoranceIntrospector());
String jsonDataString = instantiateAndSerializeObjects(mapper);
assertThat(jsonDataString, containsString("make"));
assertThat(jsonDataString, not(containsString("model")));
assertThat(jsonDataString, not(containsString("seatingCapacity")));
assertThat(jsonDataString, not(containsString("topSpeed")));
assertThat(jsonDataString, not(containsString("towingCapacity")));
}
private String instantiateAndSerializeObjects(ObjectMapper mapper) throws JsonProcessingException {
IgnoranceMixinOrIntrospection.Sedan sedan = new IgnoranceMixinOrIntrospection.Sedan("Mercedes-Benz", "S500", 5, 250.0);
IgnoranceMixinOrIntrospection.Crossover crossover = new IgnoranceMixinOrIntrospection.Crossover("BMW", "X6", 5, 250.0, 6000.0);
List<IgnoranceMixinOrIntrospection.Vehicle> vehicles = new ArrayList<>();
vehicles.add(sedan);
vehicles.add(crossover);
return mapper.writeValueAsString(vehicles);
}
}

View File

@ -1,41 +0,0 @@
package com.baeldung.jackson.inheritance;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ItemIdRemovedFromUserUnitTest {
@Test
public void givenRemoveItemJson_whenDeserialize_shouldHaveProperClassType() throws IOException {
// given
Event event = new ItemIdRemovedFromUser("1", 12345567L, "item_1", 2L);
ObjectMapper objectMapper = new ObjectMapper();
String eventJson = objectMapper.writeValueAsString(event);
// when
Event result = new ObjectMapper().readValue(eventJson, Event.class);
// then
assertTrue(result instanceof ItemIdRemovedFromUser);
assertEquals("item_1", ((ItemIdRemovedFromUser) result).getItemId());
}
@Test
public void givenAdddItemJson_whenSerialize_shouldIgnoreIdPropertyFromSuperclass() throws IOException {
// given
Event event = new ItemIdAddedToUser("1", 12345567L, "item_1", 2L);
ObjectMapper objectMapper = new ObjectMapper();
// when
String eventJson = objectMapper.writeValueAsString(event);
// then
assertFalse(eventJson.contains("id"));
}
}

View File

@ -1,60 +0,0 @@
package com.baeldung.jackson.inheritance;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.baeldung.jackson.inheritance.SubTypeConstructorStructure.Car;
import com.baeldung.jackson.inheritance.SubTypeConstructorStructure.Fleet;
import com.baeldung.jackson.inheritance.SubTypeConstructorStructure.Truck;
import com.baeldung.jackson.inheritance.SubTypeConstructorStructure.Vehicle;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator;
import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator;
public class SubTypeHandlingUnitTest {
@Test
public void givenSubTypes_whenConvertingObjects_thenDataValuesArePreserved() {
ObjectMapper mapper = new ObjectMapper();
SubTypeConversionStructure.Car car = new SubTypeConversionStructure.Car("Mercedes-Benz", "S500", 5, 250.0);
SubTypeConversionStructure.Truck truck = mapper.convertValue(car, SubTypeConversionStructure.Truck.class);
assertEquals("Mercedes-Benz", truck.getMake());
assertEquals("S500", truck.getModel());
}
@Test
public void givenSubType_whenNotUsingNoArgsConstructors_thenSucceed() throws IOException {
ObjectMapper mapper = new ObjectMapper();
PolymorphicTypeValidator ptv = BasicPolymorphicTypeValidator.builder()
.allowIfSubType("com.baeldung.jackson.inheritance")
.allowIfSubType("java.util.ArrayList")
.build();
mapper.activateDefaultTyping(ptv, ObjectMapper.DefaultTyping.NON_FINAL);
Car car = new Car("Mercedes-Benz", "S500", 5, 250.0);
Truck truck = new Truck("Isuzu", "NQR", 7500.0);
List<Vehicle> vehicles = new ArrayList<>();
vehicles.add(car);
vehicles.add(truck);
Fleet serializedFleet = new Fleet();
serializedFleet.setVehicles(vehicles);
String jsonDataString = mapper.writeValueAsString(serializedFleet);
mapper.readValue(jsonDataString, Fleet.class);
Fleet deserializedFleet = mapper.readValue(jsonDataString, Fleet.class);
assertThat(deserializedFleet.getVehicles().get(0), instanceOf(Car.class));
assertThat(deserializedFleet.getVehicles().get(1), instanceOf(Truck.class));
}
}

View File

@ -1,67 +0,0 @@
package com.baeldung.jackson.inheritance;
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.instanceOf;
import org.junit.Test;
import java.util.List;
import java.util.ArrayList;
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator;
import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator;
public class TypeInfoInclusionUnitTest {
@Test
public void givenTypeInfo_whenAnnotatingGlobally_thenTypesAreCorrectlyRecovered() throws IOException {
ObjectMapper mapper = new ObjectMapper();
PolymorphicTypeValidator ptv = BasicPolymorphicTypeValidator.builder()
.allowIfSubType("com.baeldung.jackson.inheritance")
.allowIfSubType("java.util.ArrayList")
.build();
mapper.activateDefaultTyping(ptv, ObjectMapper.DefaultTyping.NON_FINAL);
TypeInfoStructure.Car car = new TypeInfoStructure.Car("Mercedes-Benz", "S500", 5, 250.0);
TypeInfoStructure.Truck truck = new TypeInfoStructure.Truck("Isuzu", "NQR", 7500.0);
List<TypeInfoStructure.Vehicle> vehicles = new ArrayList<>();
vehicles.add(car);
vehicles.add(truck);
TypeInfoStructure.Fleet serializedFleet = new TypeInfoStructure.Fleet();
serializedFleet.setVehicles(vehicles);
String jsonDataString = mapper.writeValueAsString(serializedFleet);
TypeInfoStructure.Fleet deserializedFleet = mapper.readValue(jsonDataString, TypeInfoStructure.Fleet.class);
assertThat(deserializedFleet.getVehicles()
.get(0), instanceOf(TypeInfoStructure.Car.class));
assertThat(deserializedFleet.getVehicles()
.get(1), instanceOf(TypeInfoStructure.Truck.class));
}
@Test
public void givenTypeInfo_whenAnnotatingPerClass_thenTypesAreCorrectlyRecovered() throws IOException {
ObjectMapper mapper = new ObjectMapper();
TypeInfoAnnotatedStructure.Car car = new TypeInfoAnnotatedStructure.Car("Mercedes-Benz", "S500", 5, 250.0);
TypeInfoAnnotatedStructure.Truck truck = new TypeInfoAnnotatedStructure.Truck("Isuzu", "NQR", 7500.0);
List<TypeInfoAnnotatedStructure.Vehicle> vehicles = new ArrayList<>();
vehicles.add(car);
vehicles.add(truck);
TypeInfoAnnotatedStructure.Fleet serializedFleet = new TypeInfoAnnotatedStructure.Fleet();
serializedFleet.setVehicles(vehicles);
String jsonDataString = mapper.writeValueAsString(serializedFleet);
TypeInfoAnnotatedStructure.Fleet deserializedFleet = mapper.readValue(jsonDataString, TypeInfoAnnotatedStructure.Fleet.class);
assertThat(deserializedFleet.getVehicles()
.get(0), instanceOf(TypeInfoAnnotatedStructure.Car.class));
assertThat(deserializedFleet.getVehicles()
.get(1), instanceOf(TypeInfoAnnotatedStructure.Truck.class));
}
}

View File

@ -1,38 +0,0 @@
package com.baeldung.jackson.jacksonvsgson;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import static org.junit.Assert.assertEquals;
public class JacksonDeserializeUnitTest {
@Test
public void whenSimpleDeserialize_thenCorrect() throws IOException {
final String jsonInput = "{\"imdbId\":\"tt0472043\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}";
final ObjectMapper mapper = new ObjectMapper();
final Movie movie = mapper.readValue(jsonInput, Movie.class);
final String expectedOutput = "Movie [imdbId=tt0472043, director=null, actors=[ActorJackson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 11:00:00 GMT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]";
assertEquals(expectedOutput, movie.toString());
}
@Test
public void whenCustomDeserialize_thenCorrect() throws IOException {
final String jsonInput = "{\"imdbId\":\"tt0472043\",\"director\":\"Mel Gibson\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}";
final ObjectMapper mapper = new ObjectMapper();
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
mapper.setDateFormat(df);
final Movie movie = mapper.readValue(jsonInput, Movie.class);
final String expectedOutput = "Movie [imdbId=tt0472043, director=Mel Gibson, actors=[ActorJackson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 11:00:00 GMT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]";
assertEquals(expectedOutput, movie.toString());
}
}

View File

@ -1,58 +0,0 @@
package com.baeldung.jackson.jacksonvsgson;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.TimeZone;
import org.junit.Assert;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
public class JacksonSerializeUnitTest {
@Test
public void whenSimpleSerialize_thenCorrect() throws JsonProcessingException, ParseException {
final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
final ActorJackson rudyYoungblood = new ActorJackson("nm2199632", sdf.parse("21-09-1982"), Arrays.asList("Apocalypto", "Beatdown", "Wind Walkers"));
final Movie movie = new Movie("tt0472043", "Mel Gibson", Arrays.asList(rudyYoungblood));
final ObjectMapper mapper = new ObjectMapper();
final String jsonResult = mapper.writeValueAsString(movie);
final String expectedOutput = "{\"imdbId\":\"tt0472043\",\"director\":\"Mel Gibson\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":401414400000,\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}";
Assert.assertEquals(jsonResult, expectedOutput);
}
@Test
public void whenCustomSerialize_thenCorrect() throws ParseException, IOException {
final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
final ActorJackson rudyYoungblood = new ActorJackson("nm2199632", sdf.parse("21-09-1982"), Arrays.asList("Apocalypto", "Beatdown", "Wind Walkers"));
final MovieWithNullValue movieWithNullValue = new MovieWithNullValue(null, "Mel Gibson", Arrays.asList(rudyYoungblood));
final SimpleModule module = new SimpleModule();
module.addSerializer(new ActorJacksonSerializer(ActorJackson.class));
final ObjectMapper mapper = new ObjectMapper();
final String jsonResult = mapper.registerModule(module)
.writer(new DefaultPrettyPrinter())
.writeValueAsString(movieWithNullValue);
final Object json = mapper.readValue("{\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"21-09-1982\",\"N° Film: \":3,\"filmography\":\"Apocalypto-Beatdown-Wind Walkers\"}],\"imdbID\":null}", Object.class);
final String expectedOutput = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT)
.writeValueAsString(json);
Assert.assertEquals(jsonResult, expectedOutput);
}
}

View File

@ -1,126 +0,0 @@
package com.baeldung.jackson.jsoncompare;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.Comparator;
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.NumericNode;
import com.fasterxml.jackson.databind.node.TextNode;
public class JsonCompareUnitTest {
@Test
public void givenTwoSameJsonDataObjects_whenCompared_thenAreEqual() throws IOException {
ObjectMapper mapper = new ObjectMapper();
String s1 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\", \"age\": 34 }}";
String s2 = "{\"employee\": {\"id\": \"1212\",\"age\": 34, \"fullName\": \"John Miles\" }}";
JsonNode actualObj1 = mapper.readTree(s1);
JsonNode actualObj2 = mapper.readTree(s2);
assertEquals(actualObj1, actualObj2);
}
@Test
public void givenTwoSameNestedJsonDataObjects_whenCompared_thenEqual() throws IOException {
ObjectMapper mapper = new ObjectMapper();
String s1 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34, \"contact\":{\"email\": \"john@xyz.com\",\"phone\": \"9999999999\"} }}";
String s2 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34, \"contact\":{\"email\": \"john@xyz.com\",\"phone\": \"9999999999\"} }}";
JsonNode actualObj1 = mapper.readTree(s1);
JsonNode actualObj2 = mapper.readTree(s2);
assertEquals(actualObj1, actualObj2);
}
@Test
public void givenTwoSameListJsonDataObjects_whenCompared_thenEqual() throws IOException {
ObjectMapper mapper = new ObjectMapper();
String s1 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34, \"skills\":[\"Java\", \"C++\", \"Python\"] }}";
String s2 = "{\"employee\": {\"id\": \"1212\",\"fullName\": \"John Miles\",\"age\": 34, \"skills\":[\"Java\", \"C++\", \"Python\"] }}";
JsonNode actualObj1 = mapper.readTree(s1);
JsonNode actualObj2 = mapper.readTree(s2);
assertEquals(actualObj1, actualObj2);
}
@Test
public void givenTwoJsonDataObjects_whenComparedUsingCustomNumericNodeComparator_thenEqual() throws IOException {
ObjectMapper mapper = new ObjectMapper();
String s1 = "{\"name\": \"John\",\"score\":5.0}";
String s2 = "{\"name\": \"John\",\"score\":5}";
JsonNode actualObj1 = mapper.readTree(s1);
JsonNode actualObj2 = mapper.readTree(s2);
NumericNodeComparator cmp = new NumericNodeComparator();
assertNotEquals(actualObj1, actualObj2);
assertTrue(actualObj1.equals(cmp, actualObj2));
}
public class NumericNodeComparator implements Comparator<JsonNode> {
@Override
public int compare(JsonNode o1, JsonNode o2) {
if (o1.equals(o2)) {
return 0;
}
if ((o1 instanceof NumericNode) && (o2 instanceof NumericNode)) {
Double d1 = ((NumericNode) o1).asDouble();
Double d2 = ((NumericNode) o2).asDouble();
if (d1.compareTo(d2) == 0) {
return 0;
}
}
return 1;
}
}
@Test
public void givenTwoJsonDataObjects_whenComparedUsingCustomTextNodeComparator_thenEqual() throws IOException {
ObjectMapper mapper = new ObjectMapper();
String s1 = "{\"name\": \"JOHN\",\"score\":5}";
String s2 = "{\"name\": \"John\",\"score\":5}";
JsonNode actualObj1 = mapper.readTree(s1);
JsonNode actualObj2 = mapper.readTree(s2);
TextNodeComparator cmp = new TextNodeComparator();
assertNotEquals(actualObj1, actualObj2);
assertTrue(actualObj1.equals(cmp, actualObj2));
}
public class TextNodeComparator implements Comparator<JsonNode> {
@Override
public int compare(JsonNode o1, JsonNode o2) {
if (o1.equals(o2)) {
return 0;
}
if ((o1 instanceof TextNode) && (o2 instanceof TextNode)) {
String s1 = ((TextNode) o1).asText();
String s2 = ((TextNode) o2).asText();
if (s1.equalsIgnoreCase(s2)) {
return 0;
}
}
return 1;
}
}
}

View File

@ -1,53 +0,0 @@
package com.baeldung.jackson.jsonnode;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
class AsTextVsAsStringUnitTest {
@Test
void shouldUseAsText() throws JsonProcessingException {
String json = "{\"name\":\"John\",\"age\":30}";
JsonNode node = new ObjectMapper().readTree(json);
String name = node.get("name")
.asText();
String age = node.get("age")
.asText();
String jsonText = node.asText();
assertThat(jsonText).isEmpty();
assertThat(name).isEqualTo("John");
assertThat(age).isEqualTo("30");
}
@Test
void shouldUseAsTextWithEscapeCharacters() throws JsonProcessingException {
String specialCharsJson = "{\"text\":\"Hello \\\"world\\\" !\"}";
JsonNode specialCharsNode = new ObjectMapper().readTree(specialCharsJson);
String specialCharsJsonAsText = specialCharsNode.get("text")
.asText();
String specialCharsJsonToString = specialCharsNode.get("text")
.toString();
assertThat(specialCharsJsonAsText).isEqualTo("Hello \"world\" !");
assertThat(specialCharsJsonToString).isEqualTo("\"Hello \\\"world\\\" !\"");
}
@Test
void shouldUseToString() throws JsonProcessingException {
String json = "{\"name\":\"John\",\"age\":30}";
JsonNode node = new ObjectMapper().readTree(json);
String jsonString = node.toString();
String name = node.get("name")
.toString();
String age = node.get("age")
.toString();
assertThat(jsonString).isEqualTo("{\"name\":\"John\",\"age\":30}");
assertThat(name).isEqualTo("\"John\"");
assertThat(age).isEqualTo("30");
}
}

View File

@ -1,85 +0,0 @@
package com.baeldung.jackson.jsonnode;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.util.List;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class GetAllKeysFromJSONUnitTest {
private static String json = "{\r\n" + " \"Name\":\"Craig\",\r\n" + " \"Age\":10,\r\n" + " \"BookInterests\":[\r\n" + " {\r\n" + " \"Book\":\"The Kite Runner\",\r\n" + " \"Author\":\"Khaled Hosseini\"\r\n" + " },\r\n"
+ " {\r\n" + " \"Book\":\"Harry Potter\",\r\n" + " \"Author\":\"J. K. Rowling\"\r\n" + " }\r\n" + " ],\r\n" + " \"FoodInterests\":{\r\n" + " \"Breakfast\":[\r\n" + " {\r\n"
+ " \"Bread\":\"Whole wheat\",\r\n" + " \"Beverage\":\"Fruit juice\"\r\n" + " },\r\n" + " {\r\n" + " \"Sandwich\":\"Vegetable Sandwich\",\r\n" + " \"Beverage\":\"Coffee\"\r\n"
+ " }\r\n" + " ]\r\n" + " }\r\n" + "}";
private static ObjectMapper mapper = new ObjectMapper();
private static GetAllKeysFromJSON getAllKeysFromJSONUtil = new GetAllKeysFromJSON();
// Top level keys : [Name, Age, BookInterests, FoodInterests]
// All keys: [Name, Age, BookInterests, Book, Author, Book, Author, FoodInterests, Breakfast, Bread, Beverage, Sandwich, Beverage]
@Test
public void givenAJsonNode_whenUsingFieldNamesMethod_thenWeGetTopFieldNames() {
List<String> keys;
try {
keys = getAllKeysFromJSONUtil.getKeysInJsonUsingJsonNodeFieldNames(json, mapper);
assertEquals(4, keys.size());
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
@Test
public void givenAJsonNode_whenUsingFieldNamesMethodForAllNodes_thenWeGetAllFieldNames() {
List<String> keys;
try {
keys = getAllKeysFromJSONUtil.getAllKeysInJsonUsingJsonNodeFieldNames(json, mapper);
assertEquals(13, keys.size());
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
@Test
public void givenAJsonNode_whenUsingFieldsMethod_thenWeGetAllFieldNames() {
List<String> keys;
try {
keys = getAllKeysFromJSONUtil.getAllKeysInJsonUsingJsonNodeFields(json, mapper);
assertEquals(13, keys.size());
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
@Test
public void givenAJsonNode_whenUsingJsonParserMethod_thenWeGetAllFieldNames() {
List<String> keys;
try {
keys = getAllKeysFromJSONUtil.getKeysInJsonUsingJsonParser(json, mapper);
assertEquals(13, keys.size());
keys = getAllKeysFromJSONUtil.getKeysInJsonUsingJsonParser(json);
assertEquals(13, keys.size());
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void givenAJsonNode_whenUsingMaps_thenWeGetAllFieldNames() {
List<String> keys;
try {
keys = getAllKeysFromJSONUtil.getKeysInJsonUsingMaps(json, mapper);
assertEquals(13, keys.size());
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}

View File

@ -1,48 +0,0 @@
package com.baeldung.jackson.jsonnode;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import org.junit.jupiter.api.Assertions;
import java.util.Iterator;
import org.junit.Test;
public class RemoveJsonElementsUnitTest {
@Test
public void given_JsonData_whenUsingJackson_thenRemoveElementByKey() throws JsonProcessingException {
String json = "{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}";
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(json);
ObjectNode object = (ObjectNode) jsonNode;
object.remove("age");
String updatedJson = objectMapper.writeValueAsString(object);
Assertions.assertEquals("{\"name\":\"John\",\"city\":\"New York\"}", updatedJson);
}
@Test
public void given_JsonData_whenUsingJackson_thenRemoveElementsByCondition() throws JsonProcessingException {
String json = "{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}";
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(json);
Iterator<JsonNode> elements = jsonNode.elements();
while (elements.hasNext()) {
JsonNode element = elements.next();
if (element.isNumber() && element.asInt() == 30) {
elements.remove();
}
}
String updatedJson = objectMapper.writeValueAsString(jsonNode);
Assertions.assertEquals("{\"name\":\"John\",\"city\":\"New York\"}", updatedJson);
}
@Test
public void given_JsonData_whenUsingJackson_thenRemoveElementFromNestedStructure() throws JsonProcessingException {
String json = "{\"name\": \"John\", \"details\": {\"age\": 30, \"city\": \"New York\"}}";
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(json);
JsonNode detailsNode = jsonNode.path("details");
((ObjectNode) detailsNode).remove("age");
String updatedJson = objectMapper.writeValueAsString(jsonNode);
Assertions.assertEquals("{\"name\":\"John\",\"details\":{\"city\":\"New York\"}}", updatedJson);
}
}

View File

@ -1,18 +0,0 @@
package com.baeldung.jackson.node;
import java.io.IOException;
import java.io.InputStream;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ExampleStructure {
private static ObjectMapper mapper = new ObjectMapper();
static JsonNode getExampleRoot() throws IOException {
InputStream exampleInput = ExampleStructure.class.getClassLoader()
.getResourceAsStream("node_example.json");
JsonNode rootNode = mapper.readTree(exampleInput);
return rootNode;
}
}

View File

@ -1,37 +0,0 @@
package com.baeldung.jackson.node;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
public class JsonNodeIteratorUnitTest {
private JsonNodeIterator onTest = new JsonNodeIterator();
private static String expectedYaml = "name: \n" +
" first: Tatu\n" +
" last: Saloranta\n" +
"title: Jackson founder\n" +
"company: FasterXML\n" +
"pets: \n" +
"- type: dog\n" +
" number: 1\n" +
"- type: fish\n" +
" number: 50";
@Test
public void givenANodeTree_whenIteratingSubNodes_thenWeFindExpected() throws IOException {
final JsonNode rootNode = ExampleStructure.getExampleRoot();
String yaml = onTest.toYaml(rootNode);
System.out.println(yaml.toString());
assertEquals(expectedYaml, yaml);
}
}

View File

@ -1,30 +0,0 @@
package com.baeldung.jackson.node;
public class NodeBean {
private int id;
private String name;
public NodeBean() {
}
public NodeBean(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -1,119 +0,0 @@
package com.baeldung.jackson.node;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class NodeOperationUnitTest {
private static ObjectMapper mapper = new ObjectMapper();
@Test
public void givenAnObject_whenConvertingIntoNode_thenCorrect() {
final NodeBean fromValue = new NodeBean(2016, "baeldung.com");
final JsonNode node = mapper.valueToTree(fromValue);
assertEquals(2016, node.get("id")
.intValue());
assertEquals("baeldung.com", node.get("name")
.textValue());
}
@Test
public void givenANode_whenWritingOutAsAJsonString_thenCorrect() throws IOException {
final String pathToTestFile = "node_to_json_test.json";
final char[] characterBuffer = new char[50];
final JsonNode node = mapper.createObjectNode();
((ObjectNode) node).put("id", 2016);
((ObjectNode) node).put("name", "baeldung.com");
try (FileWriter outputStream = new FileWriter(pathToTestFile)) {
mapper.writeValue(outputStream, node);
}
try (FileReader inputStreamForAssertion = new FileReader(pathToTestFile)) {
inputStreamForAssertion.read(characterBuffer);
}
final String textContentOfTestFile = new String(characterBuffer);
assertThat(textContentOfTestFile, containsString("2016"));
assertThat(textContentOfTestFile, containsString("baeldung.com"));
Files.delete(Paths.get(pathToTestFile));
}
@Test
public void givenANode_whenConvertingIntoAnObject_thenCorrect() throws JsonProcessingException {
final JsonNode node = mapper.createObjectNode();
((ObjectNode) node).put("id", 2016);
((ObjectNode) node).put("name", "baeldung.com");
final NodeBean toValue = mapper.treeToValue(node, NodeBean.class);
assertEquals(2016, toValue.getId());
assertEquals("baeldung.com", toValue.getName());
}
@Test
public void givenANode_whenAddingIntoATree_thenCorrect() throws IOException {
final JsonNode rootNode = ExampleStructure.getExampleRoot();
final ObjectNode addedNode = ((ObjectNode) rootNode).putObject("address");
addedNode.put("city", "Seattle")
.put("state", "Washington")
.put("country", "United States");
assertFalse(rootNode.path("address")
.isMissingNode());
assertEquals("Seattle", rootNode.path("address")
.path("city")
.textValue());
assertEquals("Washington", rootNode.path("address")
.path("state")
.textValue());
assertEquals("United States", rootNode.path("address")
.path("country")
.textValue());
}
@Test
public void givenANode_whenModifyingIt_thenCorrect() throws IOException {
final String newString = "{\"nick\": \"cowtowncoder\"}";
final JsonNode newNode = mapper.readTree(newString);
final JsonNode rootNode = ExampleStructure.getExampleRoot();
((ObjectNode) rootNode).set("name", newNode);
assertFalse(rootNode.path("name")
.path("nick")
.isMissingNode());
assertEquals("cowtowncoder", rootNode.path("name")
.path("nick")
.textValue());
}
@Test
public void givenANode_whenRemovingFromATree_thenCorrect() throws IOException {
final JsonNode rootNode = ExampleStructure.getExampleRoot();
((ObjectNode) rootNode).remove("company");
assertTrue(rootNode.path("company")
.isMissingNode());
}
}

View File

@ -1,61 +0,0 @@
package com.baeldung.jackson.optionalwithjackson;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import static io.restassured.path.json.JsonPath.from;
import java.io.IOException;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class OptionalTypeUnitTest {
ObjectMapper mapper = new ObjectMapper().registerModule(new Jdk8Module());
@Test
public void givenPresentOptional_whenSerializing_thenValueInJson() throws JsonProcessingException {
String subTitle = "The Parish Boy's Progress";
Book book = new Book();
book.setTitle("Oliver Twist");
book.setSubTitle(Optional.of(subTitle));
String result = mapper.writeValueAsString(book);
assertThat(from(result).getString("subTitle")).isEqualTo(subTitle);
}
@Test
public void givenEmptyOptional_whenSerializing_thenNullValue() throws JsonProcessingException {
Book book = new Book();
book.setTitle("Oliver Twist");
book.setSubTitle(Optional.empty());
String result = mapper.writeValueAsString(book);
assertThat(from(result).getString("subTitle")).isNull();
}
@Test
public void givenField_whenDeserializingIntoOptional_thenIsPresentWithValue() throws IOException {
String subTitle = "The Parish Boy's Progress";
String book = "{ \"title\": \"Oliver Twist\", \"subTitle\": \"" + subTitle + "\" }";
Book result = mapper.readValue(book, Book.class);
assertThat(result.getSubTitle()).isEqualTo(Optional.of(subTitle));
}
@Test
public void givenNullField_whenDeserializingIntoOptional_thenIsEmpty() throws IOException {
String book = "{ \"title\": \"Oliver Twist\", \"subTitle\": null }";
Book result = mapper.readValue(book, Book.class);
assertThat(result.getSubTitle()).isEmpty();
}
}

View File

@ -1,50 +0,0 @@
package com.baeldung.jackson.sandbox;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonPrettyPrintUnitTest {
@Test
public final void whenDeserializing_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
// final String fileName = "src/main/resources/example1.json";
final String fileName = "src/main/resources/example1.json";
new File(fileName);
printJsonFromFile(fileName);
}
//
public static void printJsonFromFile(final String fileName) {
System.out.println("-----------------");
final ObjectMapper mapper = new ObjectMapper();
try {
final Object json = mapper.readValue(readFile(fileName, StandardCharsets.UTF_8), Object.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(json));
} catch (final IOException e) {
e.printStackTrace();
}
System.out.println("-----------------");
}
static String readFile(final String path, final Charset encoding) throws IOException {
final byte[] encoded = Files.readAllBytes(Paths.get(path));
return encoding.decode(ByteBuffer.wrap(encoded))
.toString();
}
}

View File

@ -1,29 +0,0 @@
package com.baeldung.jackson.sandbox;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class SandboxUnitTest {
@Test
public final void whenDeserializing_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
final TestElement testElement = new TestElement();
testElement.setX(10);
testElement.setY("adasd");
final ObjectMapper om = new ObjectMapper();
om.setVisibility(om.getSerializationConfig()
.getDefaultVisibilityChecker()
.withFieldVisibility(JsonAutoDetect.Visibility.ANY)
.withGetterVisibility(JsonAutoDetect.Visibility.NONE));
final String serialized = om.writeValueAsString(testElement);
System.err.println(serialized);
}
}

View File

@ -1,25 +0,0 @@
package com.baeldung.jackson.sandbox;
public class TestElement {
int x;
private transient String y;
public int getX() {
return x;
}
public void setX(final int x) {
this.x = x;
}
public String getY() {
return y;
}
public void setY(final String y) {
this.y = y;
}
}

View File

@ -1,14 +0,0 @@
package com.baeldung.jackson.test;
import com.baeldung.jackson.sandbox.JacksonPrettyPrintUnitTest;
import com.baeldung.jackson.sandbox.SandboxUnitTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ // @formatter:off
JacksonPrettyPrintUnitTest.class
,SandboxUnitTest.class
}) // @formatter:on
public class UnitTestSuite {
}

View File

@ -1,5 +0,0 @@
package com.baeldung.jackson.try1;
public interface IEntity {
public int getId();
}

View File

@ -1,38 +0,0 @@
package com.baeldung.jackson.try1;
import java.io.Serializable;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
@JsonDeserialize(using = RestLoaderRequestDeserializer.class)
// @Produces(MediaType.APPLICATION_JSON)
public class RestLoaderRequest<T extends IEntity> implements Serializable {
private T entity; // entity to load field to
private String className; // actual class of entity
private String fieldName; // fieldName to lazy REST load
public String getFieldName() {
return fieldName;
}
public void setFieldName(final String fieldName) {
this.fieldName = fieldName;
}
public String getClassName() {
return className;
}
public void setClassName(final String className) {
this.className = className;
}
public T getEntity() {
return entity;
}
public void setEntity(final T entity) {
this.entity = entity;
}
}

View File

@ -1,48 +0,0 @@
package com.baeldung.jackson.try1;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
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 RestLoaderRequestDeserializer extends StdDeserializer<RestLoaderRequest<IEntity>> {
private static final long serialVersionUID = -4245207329377196889L;
public RestLoaderRequestDeserializer() {
this(null);
}
public RestLoaderRequestDeserializer(final Class<?> vc) {
super(vc);
}
@Override
public RestLoaderRequest<IEntity> deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
try {
final ObjectCodec objectCodec = jp.getCodec();
final JsonNode node = objectCodec.readTree(jp);
final String className = node.get("className")
.textValue();
final String fieldName = node.get("fieldName")
.textValue();
final Class<?> clazz = Class.forName(className);
final JsonNode rawEntityNode = node.get("entity");
// How to deserialize rawEntityNode to T based on className ?
final RestLoaderRequest<IEntity> request = new RestLoaderRequest<IEntity>();
request.setClassName(className);
request.setFieldName(fieldName);
} catch (final ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
}

View File

@ -1,29 +0,0 @@
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Author",
"description": "An author",
"type": "object",
"properties": {
"items": {
"type": "array",
"items": {
"type": "object"
}
},
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"id": {
"type": "string"
}
},
"required": [
"items",
"firstName",
"lastName",
"id"
]
}

View File

@ -1,18 +0,0 @@
{
"name": {
"first": "Tatu",
"last": "Saloranta"
},
"title": "Jackson founder",
"company": "FasterXML",
"pets": [
{
"type": "dog",
"number": 1
},
{
"type": "fish",
"number": 50
}
]
}

View File

@ -1,2 +1,2 @@
## Relevant Articles
- [@JsonSubTypes vs. Reflections for Polymorphic Deserialization in Jackson](https://www.baeldung.com/java-jackson-polymorphic-deserialization)
## 相关文章
- [Jackson 中的 @JsonSubTypes 对比多态反射反序列化](https://track.ossez.com/articles/PL-A-37491939/JsonSubTypes-vs.-Reflections-for-Polymorphic-Deserialization-in-Jackson)

View File

@ -7,9 +7,9 @@
<name>jackson-polymorphic-deserialization</name>
<parent>
<groupId>com.baeldung</groupId>
<groupId>com.ossez</groupId>
<artifactId>jackson-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
<version>0.0.2-SNAPSHOT</version>
</parent>
<dependencies>

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.polymorphic.deserialization.reflection;
package com.ossez.jackson.polymorphic.deserialization.reflection;
import com.fasterxml.jackson.annotation.JsonTypeInfo;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.polymorphic.deserialization.reflection;
package com.ossez.jackson.polymorphic.deserialization.reflection;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.polymorphic.deserialization.typeHandlingAnnotations;
package com.ossez.jackson.polymorphic.deserialization.typeHandlingAnnotations;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.polymorphic.deserialization.reflection;
package com.ossez.jackson.polymorphic.deserialization.reflection;
import static org.junit.jupiter.api.Assertions.assertEquals;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.polymorphic.deserialization.typeHandlingAnnotations;
package com.ossez.jackson.polymorphic.deserialization.typeHandlingAnnotations;
import static org.junit.jupiter.api.Assertions.assertEquals;

View File

@ -12,3 +12,8 @@
- [Jackson vs Gson](https://www.baeldung.com/jackson-vs-gson)
- [Inheritance with Jackson](https://www.baeldung.com/jackson-inheritance)
- [Working with Tree Model Nodes in Jackson](https://www.baeldung.com/jackson-json-node-tree-model)
- [Get all the Keys in a JSON String Using JsonNode](https://www.baeldung.com/java-jsonnode-get-keys)
- [Difference Between asText() and toString() in JsonNode](https://www.baeldung.com/java-jsonnode-astext-vs-tostring)
- [Deserialize Generic Type with Jackson](https://www.baeldung.com/java-deserialize-generic-type-with-jackson)
- [Setting Default Values to Null Fields in Jackson Mapping](https://www.baeldung.com/java-jackson-mapping-default-values-null-fields)
- [Removing JSON Elements With Jackson](https://www.baeldung.com/java-jackson-remove-json-elements)

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.defaultvalues;
package com.ossez.jackson.defaultvalues;
public class NonAnnotatedDefaultValue {

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.defaultvalues;
package com.ossez.jackson.defaultvalues;
import com.fasterxml.jackson.annotation.JsonSetter;
import com.fasterxml.jackson.annotation.Nulls;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.defaultvalues;
package com.ossez.jackson.defaultvalues;
public class SetterDefaultValue {

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deserialization.jsongeneric;
package com.ossez.jackson.deserialization.jsongeneric;
public class JsonResponse<T> {

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deserialization.jsongeneric;
package com.ossez.jackson.deserialization.jsongeneric;
public class User {

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.jsonnode;
package com.ossez.jackson.jsonnode;
import java.io.IOException;
import java.util.ArrayList;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.defaultvalues;
package com.ossez.jackson.defaultvalues;
import org.junit.Test;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deserialization.jsongeneric;
package com.ossez.jackson.deserialization.jsongeneric;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;

View File

@ -1,14 +1,22 @@
package com.ossez.jackson.inheritance;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import java.util.List;
import java.util.ArrayList;
import java.io.IOException;
import com.ossez.jackson.inheritance.SubTypeConstructorStructure.Car;
import com.ossez.jackson.inheritance.SubTypeConstructorStructure.Fleet;
import com.ossez.jackson.inheritance.SubTypeConstructorStructure.Truck;
import com.ossez.jackson.inheritance.SubTypeConstructorStructure.Vehicle;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator;
import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator;
public class SubTypeHandlingUnitTest {
@Test
@ -23,21 +31,30 @@ public class SubTypeHandlingUnitTest {
}
@Test
public void givenSubType_whenNotUsingNoArgsConstructors_thenSucceed() throws IOException {
public void givenSubType_whenNotUsingNoArgsConstructors_thenSucceed() throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping();
PolymorphicTypeValidator ptv = BasicPolymorphicTypeValidator.builder()
.allowIfSubType("com.baeldung.jackson.inheritance")
.allowIfSubType("java.util.ArrayList")
.build();
mapper.activateDefaultTyping(ptv, ObjectMapper.DefaultTyping.NON_FINAL);
Car car = new Car("Mercedes-Benz", "S500", 5, 250.0);
Truck truck = new Truck("Isuzu", "NQR", 7500.0);
SubTypeConstructorStructure.Car car = new SubTypeConstructorStructure.Car("Mercedes-Benz", "S500", 5, 250.0);
SubTypeConstructorStructure.Truck truck = new SubTypeConstructorStructure.Truck("Isuzu", "NQR", 7500.0);
List<SubTypeConstructorStructure.Vehicle> vehicles = new ArrayList<>();
List<Vehicle> vehicles = new ArrayList<>();
vehicles.add(car);
vehicles.add(truck);
SubTypeConstructorStructure.Fleet serializedFleet = new SubTypeConstructorStructure.Fleet();
Fleet serializedFleet = new Fleet();
serializedFleet.setVehicles(vehicles);
String jsonDataString = mapper.writeValueAsString(serializedFleet);
mapper.readValue(jsonDataString, SubTypeConstructorStructure.Fleet.class);
mapper.readValue(jsonDataString, Fleet.class);
Fleet deserializedFleet = mapper.readValue(jsonDataString, Fleet.class);
assertThat(deserializedFleet.getVehicles().get(0), instanceOf(Car.class));
assertThat(deserializedFleet.getVehicles().get(1), instanceOf(Truck.class));
}
}

View File

@ -10,12 +10,18 @@ import java.util.ArrayList;
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator;
import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator;
public class TypeInfoInclusionUnitTest {
@Test
public void givenTypeInfo_whenAnnotatingGlobally_thenTypesAreCorrectlyRecovered() throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping();
PolymorphicTypeValidator ptv = BasicPolymorphicTypeValidator.builder()
.allowIfSubType("com.baeldung.jackson.inheritance")
.allowIfSubType("java.util.ArrayList")
.build();
mapper.activateDefaultTyping(ptv, ObjectMapper.DefaultTyping.NON_FINAL);
TypeInfoStructure.Car car = new TypeInfoStructure.Car("Mercedes-Benz", "S500", 5, 250.0);
TypeInfoStructure.Truck truck = new TypeInfoStructure.Truck("Isuzu", "NQR", 7500.0);

View File

@ -22,6 +22,7 @@
<module>jackson-custom-conversions</module>
<module>jackson-exceptions</module>
<module>jackson-jr</module>
<module>jackson-polymorphic-deserialization</module>
</modules>
<dependencies>