[BAEL-19676] - Move articles out of jackson part 3
This commit is contained in:
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.jackson.entities;
|
||||
package com.baeldung.jackson.jacksonvsgson;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
+1
-3
@@ -1,11 +1,9 @@
|
||||
package com.baeldung.jackson.serialization;
|
||||
package com.baeldung.jackson.jacksonvsgson;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.baeldung.jackson.entities.ActorJackson;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.jackson.entities;
|
||||
package com.baeldung.jackson.jacksonvsgson;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.jackson.entities;
|
||||
package com.baeldung.jackson.jacksonvsgson;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package com.baeldung.jackson.objectmapper;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.baeldung.jackson.objectmapper.dto.Car;
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.baeldung.jackson.objectmapper;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import com.baeldung.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();
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package com.baeldung.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;
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.baeldung.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;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.jackson.miscellaneous.mixin;
|
||||
package com.baeldung.jackson.optionalwithjackson;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import com.baeldung.jackson.dtos.Item;
|
||||
import com.baeldung.jackson.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 ItemDeserializer extends StdDeserializer<Item> {
|
||||
|
||||
private static final long serialVersionUID = 1883547683050039861L;
|
||||
|
||||
public ItemDeserializer() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public ItemDeserializer(final Class<?> vc) {
|
||||
super(vc);
|
||||
}
|
||||
|
||||
/**
|
||||
* {"id":1,"itemNr":"theItem","owner":2}
|
||||
*/
|
||||
@Override
|
||||
public Item 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("createdBy")).numberValue();
|
||||
|
||||
return new Item(id, itemName, new User(userId, null));
|
||||
}
|
||||
|
||||
}
|
||||
-41
@@ -1,41 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import com.baeldung.jackson.dtos.ItemWithSerializer;
|
||||
import com.baeldung.jackson.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));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package com.baeldung.jackson.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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package com.baeldung.jackson.dtos;
|
||||
|
||||
import com.baeldung.jackson.deserialization.ItemDeserializerOnClass;
|
||||
import com.baeldung.jackson.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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package com.baeldung.jackson.dynamicIgnore;
|
||||
|
||||
public class Address implements Hidable {
|
||||
private String city;
|
||||
private String country;
|
||||
private boolean hidden;
|
||||
|
||||
public Address(final String city, final String country, final boolean hidden) {
|
||||
super();
|
||||
this.city = city;
|
||||
this.country = country;
|
||||
this.hidden = hidden;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public void setCity(final String city) {
|
||||
this.city = city;
|
||||
}
|
||||
|
||||
public String getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public void setCountry(final String country) {
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isHidden() {
|
||||
return hidden;
|
||||
}
|
||||
|
||||
public void setHidden(final boolean hidden) {
|
||||
this.hidden = hidden;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package com.baeldung.jackson.dynamicIgnore;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
|
||||
@JsonIgnoreProperties("hidden")
|
||||
public interface Hidable {
|
||||
boolean isHidden();
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.baeldung.jackson.dynamicIgnore;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
|
||||
public class HidableSerializer extends JsonSerializer<Hidable> {
|
||||
|
||||
private JsonSerializer<Object> defaultSerializer;
|
||||
|
||||
public HidableSerializer(final JsonSerializer<Object> serializer) {
|
||||
defaultSerializer = serializer;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serialize(final Hidable value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException {
|
||||
if (value.isHidden())
|
||||
return;
|
||||
defaultSerializer.serialize(value, jgen, provider);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty(final SerializerProvider provider, final Hidable value) {
|
||||
return (value == null || value.isHidden());
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package com.baeldung.jackson.dynamicIgnore;
|
||||
|
||||
public class Person implements Hidable {
|
||||
private String name;
|
||||
private Address address;
|
||||
private boolean hidden;
|
||||
|
||||
public Person(final String name, final Address address, final boolean hidden) {
|
||||
super();
|
||||
this.name = name;
|
||||
this.address = address;
|
||||
this.hidden = hidden;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(final String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Address getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(final Address address) {
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isHidden() {
|
||||
return hidden;
|
||||
}
|
||||
|
||||
public void setHidden(final boolean hidden) {
|
||||
this.hidden = hidden;
|
||||
}
|
||||
|
||||
}
|
||||
+1
-2
@@ -1,9 +1,8 @@
|
||||
package com.baeldung.jackson.deserialization;
|
||||
package com.baeldung.jackson.jacksonvsgson;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import com.baeldung.jackson.entities.Movie;
|
||||
import org.junit.Test;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
+1
-4
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.jackson.serialization;
|
||||
package com.baeldung.jackson.jacksonvsgson;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.text.ParseException;
|
||||
@@ -6,9 +6,6 @@ import java.text.SimpleDateFormat;
|
||||
import java.util.Arrays;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import com.baeldung.jackson.entities.ActorJackson;
|
||||
import com.baeldung.jackson.entities.Movie;
|
||||
import com.baeldung.jackson.entities.MovieWithNullValue;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package com.baeldung.jackson.jsonview;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonView;
|
||||
|
||||
public class Item {
|
||||
@JsonView(Views.Public.class)
|
||||
public int id;
|
||||
|
||||
@JsonView(Views.Public.class)
|
||||
public String itemName;
|
||||
|
||||
@JsonView(Views.Internal.class)
|
||||
public String ownerName;
|
||||
|
||||
public Item() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Item(final int id, final String itemName, final String ownerName) {
|
||||
this.id = id;
|
||||
this.itemName = itemName;
|
||||
this.ownerName = ownerName;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getItemName() {
|
||||
return itemName;
|
||||
}
|
||||
|
||||
public String getOwnerName() {
|
||||
return ownerName;
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
package com.baeldung.jackson.jsonview;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.fasterxml.jackson.databind.BeanDescription;
|
||||
import com.fasterxml.jackson.databind.SerializationConfig;
|
||||
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
|
||||
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
|
||||
|
||||
public class MyBeanSerializerModifier extends BeanSerializerModifier {
|
||||
|
||||
@Override
|
||||
public List<BeanPropertyWriter> changeProperties(final SerializationConfig config, final BeanDescription beanDesc, final List<BeanPropertyWriter> beanProperties) {
|
||||
for (int i = 0; i < beanProperties.size(); i++) {
|
||||
final BeanPropertyWriter beanPropertyWriter = beanProperties.get(i);
|
||||
if (beanPropertyWriter.getName() == "name") {
|
||||
beanProperties.set(i, new UpperCasingWriter(beanPropertyWriter));
|
||||
}
|
||||
}
|
||||
return beanProperties;
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
package com.baeldung.jackson.jsonview;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
|
||||
|
||||
public class UpperCasingWriter extends BeanPropertyWriter {
|
||||
final BeanPropertyWriter _writer;
|
||||
|
||||
public UpperCasingWriter(final BeanPropertyWriter w) {
|
||||
super(w);
|
||||
_writer = w;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serializeAsField(final Object bean, final JsonGenerator gen, final SerializerProvider prov) throws Exception {
|
||||
String value = ((User) bean).name;
|
||||
value = (value == null) ? "" : value.toUpperCase();
|
||||
gen.writeStringField("name", value);
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package com.baeldung.jackson.jsonview;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonView;
|
||||
|
||||
public class User {
|
||||
public int id;
|
||||
|
||||
@JsonView(Views.Public.class)
|
||||
public String name;
|
||||
|
||||
public User() {
|
||||
super();
|
||||
}
|
||||
|
||||
public User(final int id, final String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.baeldung.jackson.jsonview;
|
||||
|
||||
public class Views {
|
||||
public static class Public {
|
||||
}
|
||||
|
||||
public static class Internal extends Public {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
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);
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
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());
|
||||
}
|
||||
|
||||
}
|
||||
-114
@@ -1,114 +0,0 @@
|
||||
package com.baeldung.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.baeldung.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());
|
||||
}
|
||||
}
|
||||
-85
@@ -1,85 +0,0 @@
|
||||
package com.baeldung.jackson.objectmapper;
|
||||
|
||||
import com.baeldung.jackson.objectmapper.dto.Car;
|
||||
import com.baeldung.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"));
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.jackson.miscellaneous.mixin;
|
||||
package com.baeldung.jackson.optionalwithjackson;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
@@ -26,6 +26,4 @@ public class SandboxUnitTest {
|
||||
System.err.println(serialized);
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
}
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
package com.baeldung.jackson.serialization;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import com.baeldung.jackson.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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
package com.baeldung.jackson.test;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.hamcrest.CoreMatchers.not;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.jackson.deserialization.ItemDeserializer;
|
||||
import com.baeldung.jackson.dtos.Item;
|
||||
import com.baeldung.jackson.dtos.ItemWithSerializer;
|
||||
import com.baeldung.jackson.dtos.MyDto;
|
||||
import com.fasterxml.jackson.core.JsonFactory;
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
|
||||
import com.fasterxml.jackson.databind.module.SimpleModule;
|
||||
|
||||
public class JacksonDeserializationUnitTest {
|
||||
|
||||
@Test
|
||||
public final void whenDeserializingAJsonToAClass_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
|
||||
final String jsonAsString = "{\"stringValue\":\"a\",\"intValue\":1,\"booleanValue\":true}";
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final MyDto readValue = mapper.readValue(jsonAsString, MyDto.class);
|
||||
|
||||
assertNotNull(readValue);
|
||||
assertThat(readValue.getStringValue(), equalTo("a"));
|
||||
}
|
||||
|
||||
@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));
|
||||
}
|
||||
|
||||
// custom deserialization
|
||||
|
||||
@Test
|
||||
public final void whenDeserializingTheStandardRepresentation_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
|
||||
final String json = "{\"id\":1,\"itemName\":\"theItem\",\"owner\":{\"id\":2,\"name\":\"theUser\"}}";
|
||||
|
||||
final Item readValue = new ObjectMapper().readValue(json, Item.class);
|
||||
assertThat(readValue, notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenDeserializingANonStandardRepresentation_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
|
||||
final String json = "{\"id\":1,\"itemName\":\"theItem\",\"createdBy\":2}";
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final SimpleModule module = new SimpleModule();
|
||||
module.addDeserializer(Item.class, new ItemDeserializer());
|
||||
mapper.registerModule(module);
|
||||
|
||||
final Item readValue = mapper.readValue(json, Item.class);
|
||||
assertThat(readValue, notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenDeserializerIsOnClass_whenDeserializingCustomRepresentation_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
|
||||
final String json = "{\"id\":1,\"itemName\":\"theItem\",\"owner\":2}";
|
||||
|
||||
final ItemWithSerializer readValue = new ObjectMapper().readValue(json, ItemWithSerializer.class);
|
||||
assertThat(readValue, notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDeserialisingZonedDateTimeWithDefaults_thenTimeZoneIsNotPreserved() throws IOException {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
objectMapper.findAndRegisterModules();
|
||||
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
// construct a new instance of ZonedDateTime
|
||||
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin"));
|
||||
String converted = objectMapper.writeValueAsString(now);
|
||||
// restore an instance of ZonedDateTime from String
|
||||
ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
|
||||
System.out.println("serialized: " + now);
|
||||
System.out.println("restored: " + restored);
|
||||
assertThat(now, is(not(restored)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDeserialisingZonedDateTimeWithFeaturesDisabled_thenTimeZoneIsPreserved() throws IOException {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
objectMapper.findAndRegisterModules();
|
||||
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
|
||||
// construct a new instance of ZonedDateTime
|
||||
ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin"));
|
||||
String converted = objectMapper.writeValueAsString(now);
|
||||
// restore an instance of ZonedDateTime from String
|
||||
ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
|
||||
System.out.println("serialized: " + now);
|
||||
System.out.println("restored: " + restored);
|
||||
assertThat(now, is(restored));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
package com.baeldung.jackson.test;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import com.baeldung.jackson.dynamicIgnore.Address;
|
||||
import com.baeldung.jackson.dynamicIgnore.HidableSerializer;
|
||||
import com.baeldung.jackson.dynamicIgnore.Person;
|
||||
import com.baeldung.jackson.dynamicIgnore.Hidable;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.BeanDescription;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationConfig;
|
||||
import com.fasterxml.jackson.databind.module.SimpleModule;
|
||||
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
|
||||
|
||||
public class JacksonDynamicIgnoreUnitTest {
|
||||
|
||||
private ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
mapper.setSerializationInclusion(Include.NON_EMPTY);
|
||||
mapper.registerModule(new SimpleModule() {
|
||||
@Override
|
||||
public void setupModule(final SetupContext context) {
|
||||
super.setupModule(context);
|
||||
context.addBeanSerializerModifier(new BeanSerializerModifier() {
|
||||
@Override
|
||||
public JsonSerializer<?> modifySerializer(final SerializationConfig config, final BeanDescription beanDesc, final JsonSerializer<?> serializer) {
|
||||
if (Hidable.class.isAssignableFrom(beanDesc.getBeanClass())) {
|
||||
return new HidableSerializer((JsonSerializer<Object>) serializer);
|
||||
}
|
||||
return serializer;
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNotHidden_thenCorrect() throws JsonProcessingException {
|
||||
final Address ad = new Address("ny", "usa", false);
|
||||
final Person person = new Person("john", ad, false);
|
||||
final String result = mapper.writeValueAsString(person);
|
||||
|
||||
assertTrue(result.contains("name"));
|
||||
assertTrue(result.contains("john"));
|
||||
assertTrue(result.contains("address"));
|
||||
assertTrue(result.contains("usa"));
|
||||
|
||||
System.out.println("Not Hidden = " + result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddressHidden_thenCorrect() throws JsonProcessingException {
|
||||
final Address ad = new Address("ny", "usa", true);
|
||||
final Person person = new Person("john", ad, false);
|
||||
final String result = mapper.writeValueAsString(person);
|
||||
|
||||
assertTrue(result.contains("name"));
|
||||
assertTrue(result.contains("john"));
|
||||
assertFalse(result.contains("address"));
|
||||
assertFalse(result.contains("usa"));
|
||||
|
||||
System.out.println("Address Hidden = " + result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAllHidden_thenCorrect() throws JsonProcessingException {
|
||||
final Address ad = new Address("ny", "usa", false);
|
||||
final Person person = new Person("john", ad, true);
|
||||
final String result = mapper.writeValueAsString(person);
|
||||
|
||||
assertTrue(result.length() == 0);
|
||||
|
||||
System.out.println("All Hidden = " + result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSerializeList_thenCorrect() throws JsonProcessingException {
|
||||
final Address ad1 = new Address("tokyo", "jp", true);
|
||||
final Address ad2 = new Address("london", "uk", false);
|
||||
final Address ad3 = new Address("ny", "usa", false);
|
||||
final Person p1 = new Person("john", ad1, false);
|
||||
final Person p2 = new Person("tom", ad2, true);
|
||||
final Person p3 = new Person("adam", ad3, false);
|
||||
|
||||
final String result = mapper.writeValueAsString(Arrays.asList(p1, p2, p3));
|
||||
|
||||
System.out.println(result);
|
||||
}
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
package com.baeldung.jackson.test;
|
||||
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.jackson.jsonview.Item;
|
||||
import com.baeldung.jackson.jsonview.MyBeanSerializerModifier;
|
||||
import com.baeldung.jackson.jsonview.User;
|
||||
import com.baeldung.jackson.jsonview.Views;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.MapperFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.ser.BeanSerializerFactory;
|
||||
import com.fasterxml.jackson.databind.ser.SerializerFactory;
|
||||
|
||||
public class JacksonJsonViewUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenUseJsonViewToSerialize_thenCorrect() throws JsonProcessingException {
|
||||
final User user = new User(1, "John");
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
|
||||
|
||||
final String result = mapper.writerWithView(Views.Public.class)
|
||||
.writeValueAsString(user);
|
||||
|
||||
assertThat(result, containsString("John"));
|
||||
assertThat(result, not(containsString("1")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsePublicView_thenOnlyPublicSerialized() throws JsonProcessingException {
|
||||
final Item item = new Item(2, "book", "John");
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final String result = mapper.writerWithView(Views.Public.class)
|
||||
.writeValueAsString(item);
|
||||
|
||||
assertThat(result, containsString("book"));
|
||||
assertThat(result, containsString("2"));
|
||||
|
||||
assertThat(result, not(containsString("John")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUseInternalView_thenAllSerialized() throws JsonProcessingException {
|
||||
final Item item = new Item(2, "book", "John");
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final String result = mapper.writerWithView(Views.Internal.class)
|
||||
.writeValueAsString(item);
|
||||
|
||||
assertThat(result, containsString("book"));
|
||||
assertThat(result, containsString("2"));
|
||||
|
||||
assertThat(result, containsString("John"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUseJsonViewToDeserialize_thenCorrect() throws IOException {
|
||||
final String json = "{\"id\":1,\"name\":\"John\"}";
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final User user = mapper.readerWithView(Views.Public.class)
|
||||
.forType(User.class)
|
||||
.readValue(json);
|
||||
assertEquals(1, user.getId());
|
||||
assertEquals("John", user.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUseCustomJsonViewToSerialize_thenCorrect() throws JsonProcessingException {
|
||||
final User user = new User(1, "John");
|
||||
final SerializerFactory serializerFactory = BeanSerializerFactory.instance.withSerializerModifier(new MyBeanSerializerModifier());
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.setSerializerFactory(serializerFactory);
|
||||
|
||||
final String result = mapper.writerWithView(Views.Public.class)
|
||||
.writeValueAsString(user);
|
||||
assertThat(result, containsString("JOHN"));
|
||||
assertThat(result, containsString("1"));
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,7 @@ import org.junit.runners.Suite;
|
||||
|
||||
@RunWith(Suite.class)
|
||||
@Suite.SuiteClasses({ // @formatter:off
|
||||
JacksonDeserializationUnitTest.class
|
||||
,JacksonDeserializationUnitTest.class
|
||||
,JacksonPrettyPrintUnitTest.class
|
||||
JacksonPrettyPrintUnitTest.class
|
||||
,SandboxUnitTest.class
|
||||
}) // @formatter:on
|
||||
public class UnitTestSuite {
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
package com.baeldung.jackson.try1;
|
||||
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import com.baeldung.jackson.dtos.ItemWithSerializer;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class JacksonDeserializationUnitTest {
|
||||
|
||||
@Test
|
||||
public final void givenDeserializerIsOnClass_whenDeserializingCustomRepresentation_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
|
||||
final String json = "{\"id\":1,\"itemName\":\"theItem\",\"owner\":2}";
|
||||
|
||||
final ItemWithSerializer readValue = new ObjectMapper().readValue(json, ItemWithSerializer.class);
|
||||
assertThat(readValue, notNullValue());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"color": "Black",
|
||||
"type": "BMW"
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"name": {
|
||||
"first": "Tatu",
|
||||
"last": "Saloranta"
|
||||
},
|
||||
"title": "Jackson founder",
|
||||
"company": "FasterXML",
|
||||
"pets": [
|
||||
{
|
||||
"type": "dog",
|
||||
"number": 1
|
||||
},
|
||||
{
|
||||
"type": "fish",
|
||||
"number": 50
|
||||
}
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user