[BAEL-19675] - Move articles out of jackson part 2
This commit is contained in:
@@ -1,39 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization.dynamicobject;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAnySetter;
|
||||
|
||||
public class Product {
|
||||
|
||||
private String name;
|
||||
private String category;
|
||||
private Map<String, Object> details = new LinkedHashMap<>();
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getCategory() {
|
||||
return category;
|
||||
}
|
||||
|
||||
public void setCategory(String category) {
|
||||
this.category = category;
|
||||
}
|
||||
|
||||
public Map<String, Object> getDetails() {
|
||||
return details;
|
||||
}
|
||||
|
||||
@JsonAnySetter
|
||||
public void setDetail(String key, Object value) {
|
||||
details.put(key, value);
|
||||
}
|
||||
|
||||
}
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization.dynamicobject;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
|
||||
public class ProductJsonNode {
|
||||
|
||||
private String name;
|
||||
private String category;
|
||||
private JsonNode details;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getCategory() {
|
||||
return category;
|
||||
}
|
||||
|
||||
public void setCategory(String category) {
|
||||
this.category = category;
|
||||
}
|
||||
|
||||
public JsonNode getDetails() {
|
||||
return details;
|
||||
}
|
||||
|
||||
public void setDetails(JsonNode details) {
|
||||
this.details = details;
|
||||
}
|
||||
|
||||
}
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization.dynamicobject;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class ProductMap {
|
||||
|
||||
private String name;
|
||||
private String category;
|
||||
private Map<String, Object> details;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getCategory() {
|
||||
return category;
|
||||
}
|
||||
|
||||
public void setCategory(String category) {
|
||||
this.category = category;
|
||||
}
|
||||
|
||||
public Map<String, Object> getDetails() {
|
||||
return details;
|
||||
}
|
||||
|
||||
public void setDetails(Map<String, Object> details) {
|
||||
this.details = details;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization.enums;
|
||||
|
||||
public class City {
|
||||
|
||||
private Distance distance;
|
||||
|
||||
public Distance getDistance() {
|
||||
return distance;
|
||||
}
|
||||
|
||||
public void setDistance(Distance distance) {
|
||||
this.distance = distance;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization.enums;
|
||||
|
||||
public enum Distance {
|
||||
|
||||
KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001);
|
||||
|
||||
private String unit;
|
||||
private double meters;
|
||||
|
||||
private Distance(String unit, double meters) {
|
||||
this.unit = unit;
|
||||
this.meters = meters;
|
||||
}
|
||||
|
||||
public void setMeters(double meters) {
|
||||
this.meters = meters;
|
||||
}
|
||||
|
||||
public double getMeters() {
|
||||
return meters;
|
||||
}
|
||||
|
||||
public String getUnit() {
|
||||
return unit;
|
||||
}
|
||||
|
||||
public void setUnit(String unit) {
|
||||
this.unit = unit;
|
||||
}
|
||||
}
|
||||
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization.enums.customdeserializer;
|
||||
|
||||
public class City {
|
||||
|
||||
private Distance distance;
|
||||
|
||||
public Distance getDistance() {
|
||||
return distance;
|
||||
}
|
||||
|
||||
public void setDistance(Distance distance) {
|
||||
this.distance = distance;
|
||||
}
|
||||
|
||||
}
|
||||
-42
@@ -1,42 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization.enums.customdeserializer;
|
||||
|
||||
import java.io.IOException;
|
||||
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;
|
||||
|
||||
public class CustomEnumDeserializer extends StdDeserializer<Distance> {
|
||||
|
||||
private static final long serialVersionUID = -1166032307856492833L;
|
||||
|
||||
public CustomEnumDeserializer() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public CustomEnumDeserializer(Class<?> c) {
|
||||
super(c);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Distance deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
|
||||
|
||||
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
|
||||
|
||||
String unit = node.get("unit").asText();
|
||||
double meters = node.get("meters").asDouble();
|
||||
|
||||
for (Distance distance : Distance.values()) {
|
||||
|
||||
if (distance.getUnit().equals(unit) &&
|
||||
Double.compare(distance.getMeters(), meters) == 0) {
|
||||
|
||||
return distance;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization.enums.customdeserializer;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
|
||||
@JsonDeserialize(using = CustomEnumDeserializer.class)
|
||||
public enum Distance {
|
||||
|
||||
KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001);
|
||||
|
||||
private String unit;
|
||||
private double meters;
|
||||
|
||||
private Distance(String unit, double meters) {
|
||||
this.unit = unit;
|
||||
this.meters = meters;
|
||||
}
|
||||
|
||||
public double getMeters() {
|
||||
return meters;
|
||||
}
|
||||
|
||||
public void setMeters(double meters) {
|
||||
this.meters = meters;
|
||||
}
|
||||
|
||||
public String getUnit() {
|
||||
return unit;
|
||||
}
|
||||
|
||||
public void setUnit(String unit) {
|
||||
this.unit = unit;
|
||||
}
|
||||
}
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization.enums.jsoncreator;
|
||||
|
||||
public class City {
|
||||
|
||||
private Distance distance;
|
||||
|
||||
public Distance getDistance() {
|
||||
return distance;
|
||||
}
|
||||
|
||||
public void setDistance(Distance distance) {
|
||||
this.distance = distance;
|
||||
}
|
||||
|
||||
}
|
||||
-48
@@ -1,48 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization.enums.jsoncreator;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
public enum Distance {
|
||||
|
||||
KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001);
|
||||
|
||||
private String unit;
|
||||
private double meters;
|
||||
|
||||
private Distance(String unit, double meters) {
|
||||
this.unit = unit;
|
||||
this.meters = meters;
|
||||
}
|
||||
|
||||
public void setMeters(double meters) {
|
||||
this.meters = meters;
|
||||
}
|
||||
|
||||
public double getMeters() {
|
||||
return meters;
|
||||
}
|
||||
|
||||
public String getUnit() {
|
||||
return unit;
|
||||
}
|
||||
|
||||
public void setUnit(String unit) {
|
||||
this.unit = unit;
|
||||
}
|
||||
|
||||
@JsonCreator
|
||||
public static Distance forValues(@JsonProperty("unit") String unit, @JsonProperty("meters") double meters) {
|
||||
|
||||
for (Distance distance : Distance.values()) {
|
||||
if (distance.unit.equals(unit) && Double.compare(distance.meters, meters) == 0) {
|
||||
|
||||
return distance;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization.enums.jsonproperty;
|
||||
|
||||
public class City {
|
||||
|
||||
private Distance distance;
|
||||
|
||||
public Distance getDistance() {
|
||||
return distance;
|
||||
}
|
||||
|
||||
public void setDistance(Distance distance) {
|
||||
this.distance = distance;
|
||||
}
|
||||
|
||||
}
|
||||
-51
@@ -1,51 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization.enums.jsonproperty;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
public enum Distance {
|
||||
|
||||
@JsonProperty("distance-in-km")
|
||||
KILOMETER("km", 1000),
|
||||
|
||||
@JsonProperty("distance-in-miles")
|
||||
MILE("miles", 1609.34),
|
||||
|
||||
@JsonProperty("distance-in-meters")
|
||||
METER("meters", 1),
|
||||
|
||||
@JsonProperty("distance-in-inches")
|
||||
INCH("inches", 0.0254),
|
||||
|
||||
@JsonProperty("distance-in-cm")
|
||||
CENTIMETER("cm", 0.01),
|
||||
|
||||
@JsonProperty("distance-in-mm")
|
||||
MILLIMETER("mm", 0.001);
|
||||
|
||||
private String unit;
|
||||
private double meters;
|
||||
|
||||
private Distance(String unit, double meters) {
|
||||
this.unit = unit;
|
||||
this.meters = meters;
|
||||
}
|
||||
|
||||
public void setMeters(double meters) {
|
||||
this.meters = meters;
|
||||
}
|
||||
|
||||
public double getMeters() {
|
||||
return meters;
|
||||
}
|
||||
|
||||
public String getUnit() {
|
||||
return unit;
|
||||
}
|
||||
|
||||
public void setUnit(String unit) {
|
||||
this.unit = unit;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization.enums.jsonvalue;
|
||||
|
||||
public class City {
|
||||
|
||||
private Distance distance;
|
||||
|
||||
public Distance getDistance() {
|
||||
return distance;
|
||||
}
|
||||
|
||||
public void setDistance(Distance distance) {
|
||||
this.distance = distance;
|
||||
}
|
||||
|
||||
}
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization.enums.jsonvalue;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
|
||||
public enum Distance {
|
||||
|
||||
KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001);
|
||||
|
||||
private String unit;
|
||||
private double meters;
|
||||
|
||||
private Distance(String unit, double meters) {
|
||||
this.unit = unit;
|
||||
this.meters = meters;
|
||||
}
|
||||
|
||||
public void setMeters(double meters) {
|
||||
this.meters = meters;
|
||||
}
|
||||
|
||||
@JsonValue
|
||||
public double getMeters() {
|
||||
return meters;
|
||||
}
|
||||
|
||||
public String getUnit() {
|
||||
return unit;
|
||||
}
|
||||
|
||||
public void setUnit(String unit) {
|
||||
this.unit = unit;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization.immutable;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
public class Employee {
|
||||
|
||||
private final long id;
|
||||
private final String name;
|
||||
|
||||
@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
|
||||
public Employee(@JsonProperty("id") long id, @JsonProperty("name") String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization.immutable;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
|
||||
|
||||
@JsonDeserialize(builder = Person.Builder.class)
|
||||
public class Person {
|
||||
|
||||
private final String name;
|
||||
private final Integer age;
|
||||
|
||||
private Person(String name, Integer age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public Integer getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
@JsonPOJOBuilder
|
||||
static class Builder {
|
||||
String name;
|
||||
Integer age;
|
||||
|
||||
Builder withName(String name) {
|
||||
this.name = name;
|
||||
return this;
|
||||
}
|
||||
|
||||
Builder withAge(Integer age) {
|
||||
this.age = age;
|
||||
return this;
|
||||
}
|
||||
|
||||
Person build() {
|
||||
return new Person(name, age);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.baeldung.jackson.entities;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import com.baeldung.jackson.serialization.MyPairDeserializer;
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
|
||||
public class ClassWithAMap {
|
||||
|
||||
@JsonProperty("map")
|
||||
@JsonDeserialize(keyUsing = MyPairDeserializer.class)
|
||||
private final Map<MyPair, String> map;
|
||||
|
||||
@JsonCreator
|
||||
public ClassWithAMap(Map<MyPair, String> map) {
|
||||
this.map = map;
|
||||
}
|
||||
|
||||
public Map<MyPair, String> getMap() {
|
||||
return map;
|
||||
}
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
package com.baeldung.jackson.entities;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
|
||||
public class MyPair {
|
||||
|
||||
private String first;
|
||||
private String second;
|
||||
|
||||
public MyPair(String first, String second) {
|
||||
this.first = first;
|
||||
this.second = second;
|
||||
}
|
||||
|
||||
public MyPair(String both) {
|
||||
String[] pairs = both.split("and");
|
||||
this.first = pairs[0].trim();
|
||||
this.second = pairs[1].trim();
|
||||
}
|
||||
|
||||
@Override
|
||||
@JsonValue
|
||||
public String toString() {
|
||||
return first + " and " + second;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + ((first == null) ? 0 : first.hashCode());
|
||||
result = prime * result + ((second == null) ? 0 : second.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;
|
||||
}
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
if (!(obj instanceof MyPair)) {
|
||||
return false;
|
||||
}
|
||||
MyPair other = (MyPair) obj;
|
||||
if (first == null) {
|
||||
if (other.first != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (!first.equals(other.first)) {
|
||||
return false;
|
||||
}
|
||||
if (second == null) {
|
||||
if (other.second != null) {
|
||||
return false;
|
||||
}
|
||||
} else if (!second.equals(other.second)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public String getFirst() {
|
||||
return first;
|
||||
}
|
||||
|
||||
public void setFirst(String first) {
|
||||
this.first = first;
|
||||
}
|
||||
|
||||
public String getSecond() {
|
||||
return second;
|
||||
}
|
||||
|
||||
public void setSecond(String second) {
|
||||
this.second = second;
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
package com.baeldung.jackson.enums;
|
||||
|
||||
import com.baeldung.jackson.serialization.DistanceSerializer;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
|
||||
/**
|
||||
* Use @JsonFormat to handle representation of Enum as JSON (available since Jackson 2.1.2)
|
||||
* Use @JsonSerialize to configure a custom Jackson serializer
|
||||
*/
|
||||
// @JsonFormat(shape = JsonFormat.Shape.OBJECT)
|
||||
@JsonSerialize(using = DistanceSerializer.class)
|
||||
public enum Distance {
|
||||
KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001);
|
||||
|
||||
private String unit;
|
||||
private final double meters;
|
||||
|
||||
private Distance(String unit, double meters) {
|
||||
this.unit = unit;
|
||||
this.meters = meters;
|
||||
}
|
||||
|
||||
/**
|
||||
* Use @JsonValue to control marshalling output for an enum
|
||||
*/
|
||||
// @JsonValue
|
||||
public double getMeters() {
|
||||
return meters;
|
||||
}
|
||||
|
||||
public String getUnit() {
|
||||
return unit;
|
||||
}
|
||||
|
||||
public void setUnit(String unit) {
|
||||
this.unit = unit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Usage example: Distance.MILE.convertFromMeters(1205.5);
|
||||
*/
|
||||
public double convertFromMeters(double distanceInMeters) {
|
||||
return distanceInMeters / meters;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Usage example: Distance.MILE.convertToMeters(0.5);
|
||||
*/
|
||||
public double convertToMeters(double distanceInMeters) {
|
||||
return distanceInMeters * meters;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
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,33 +0,0 @@
|
||||
package com.baeldung.jackson.serialization;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import com.baeldung.jackson.enums.Distance;
|
||||
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 DistanceSerializer extends StdSerializer<Distance> {
|
||||
|
||||
private static final long serialVersionUID = 1376504304439963619L;
|
||||
|
||||
public DistanceSerializer() {
|
||||
super(Distance.class);
|
||||
}
|
||||
|
||||
public DistanceSerializer(Class<Distance> t) {
|
||||
super(t);
|
||||
}
|
||||
|
||||
public void serialize(Distance distance, JsonGenerator generator, SerializerProvider provider) throws IOException, JsonProcessingException {
|
||||
generator.writeStartObject();
|
||||
generator.writeFieldName("name");
|
||||
generator.writeString(distance.name());
|
||||
generator.writeFieldName("unit");
|
||||
generator.writeString(distance.getUnit());
|
||||
generator.writeFieldName("meters");
|
||||
generator.writeNumber(distance.getMeters());
|
||||
generator.writeEndObject();
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.baeldung.jackson.serialization;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import com.baeldung.jackson.entities.MyPair;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.KeyDeserializer;
|
||||
|
||||
public class MyPairDeserializer extends KeyDeserializer {
|
||||
|
||||
@Override
|
||||
public MyPair deserializeKey(String key, DeserializationContext ctxt) throws IOException, JsonProcessingException {
|
||||
|
||||
return new MyPair(key);
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.baeldung.jackson.serialization;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringWriter;
|
||||
|
||||
import com.baeldung.jackson.entities.MyPair;
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
|
||||
public class MyPairSerializer extends JsonSerializer<MyPair> {
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@Override
|
||||
public void serialize(MyPair value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
|
||||
StringWriter writer = new StringWriter();
|
||||
mapper.writeValue(writer, value);
|
||||
gen.writeFieldName(writer.toString());
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.baeldung.jackson.xmlToJson;
|
||||
|
||||
public enum Color {
|
||||
PINK, BLUE, YELLOW, RED;
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package com.baeldung.jackson.xmlToJson;
|
||||
|
||||
public class Flower {
|
||||
|
||||
private String name;
|
||||
|
||||
private Color color;
|
||||
|
||||
private Integer petals;
|
||||
|
||||
public Flower() { }
|
||||
|
||||
public Flower(String name, Color color, Integer petals) {
|
||||
this.name = name;
|
||||
this.color = color;
|
||||
this.petals = petals;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Color getColor() {
|
||||
return color;
|
||||
}
|
||||
|
||||
public void setColor(Color color) {
|
||||
this.color = color;
|
||||
}
|
||||
|
||||
public Integer getPetals() {
|
||||
return petals;
|
||||
}
|
||||
|
||||
public void setPetals(Integer petals) {
|
||||
this.petals = petals;
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package com.baeldung.jackson.date;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
|
||||
|
||||
public class CustomDateDeserializer extends StdDeserializer<Date> {
|
||||
|
||||
private static final long serialVersionUID = -5451717385630622729L;
|
||||
private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
|
||||
|
||||
public CustomDateDeserializer() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public CustomDateDeserializer(final Class<?> vc) {
|
||||
super(vc);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Date deserialize(final JsonParser jsonparser, final DeserializationContext context) throws IOException, JsonProcessingException {
|
||||
final String date = jsonparser.getText();
|
||||
try {
|
||||
return formatter.parse(date);
|
||||
} catch (final ParseException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.baeldung.jackson.date;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
|
||||
|
||||
public class CustomDateSerializer extends StdSerializer<Date> {
|
||||
|
||||
private static final long serialVersionUID = -2894356342227378312L;
|
||||
private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
|
||||
|
||||
public CustomDateSerializer() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public CustomDateSerializer(final Class<Date> t) {
|
||||
super(t);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException, JsonProcessingException {
|
||||
gen.writeString(formatter.format(value));
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package com.baeldung.jackson.date;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import org.joda.time.format.DateTimeFormat;
|
||||
import org.joda.time.format.DateTimeFormatter;
|
||||
|
||||
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 CustomDateTimeSerializer extends StdSerializer<DateTime> {
|
||||
|
||||
private static final long serialVersionUID = -3927232057990121460L;
|
||||
|
||||
public CustomDateTimeSerializer() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public CustomDateTimeSerializer(final Class<DateTime> t) {
|
||||
super(t);
|
||||
}
|
||||
|
||||
private static DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");
|
||||
|
||||
@Override
|
||||
public void serialize(final DateTime value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException, JsonProcessingException {
|
||||
gen.writeString(formatter.print(value));
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.baeldung.jackson.date;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
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 CustomLocalDateTimeSerializer extends StdSerializer<LocalDateTime> {
|
||||
|
||||
private static final long serialVersionUID = -7449444168934819290L;
|
||||
private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
|
||||
|
||||
public CustomLocalDateTimeSerializer() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public CustomLocalDateTimeSerializer(final Class<LocalDateTime> t) {
|
||||
super(t);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void serialize(final LocalDateTime value, final JsonGenerator gen, final SerializerProvider arg2) throws IOException, JsonProcessingException {
|
||||
gen.writeString(formatter.format(value));
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package com.baeldung.jackson.date;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class Event {
|
||||
public String name;
|
||||
public Date eventDate;
|
||||
|
||||
public Event() {
|
||||
super();
|
||||
}
|
||||
|
||||
public Event(final String name, final Date eventDate) {
|
||||
this.name = name;
|
||||
this.eventDate = eventDate;
|
||||
}
|
||||
|
||||
public Date getEventDate() {
|
||||
return eventDate;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.baeldung.jackson.date;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
|
||||
public class EventWithFormat {
|
||||
public String name;
|
||||
|
||||
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
|
||||
public Date eventDate;
|
||||
|
||||
public EventWithFormat() {
|
||||
super();
|
||||
}
|
||||
|
||||
public EventWithFormat(final String name, final Date eventDate) {
|
||||
this.name = name;
|
||||
this.eventDate = eventDate;
|
||||
}
|
||||
|
||||
public Date getEventDate() {
|
||||
return eventDate;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.baeldung.jackson.date;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
|
||||
public class EventWithJodaTime {
|
||||
public String name;
|
||||
|
||||
@JsonSerialize(using = CustomDateTimeSerializer.class)
|
||||
public DateTime eventDate;
|
||||
|
||||
public EventWithJodaTime() {
|
||||
super();
|
||||
}
|
||||
|
||||
public EventWithJodaTime(final String name, final DateTime eventDate) {
|
||||
this.name = name;
|
||||
this.eventDate = eventDate;
|
||||
}
|
||||
|
||||
public DateTime getEventDate() {
|
||||
return eventDate;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.baeldung.jackson.date;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
|
||||
public class EventWithLocalDateTime {
|
||||
public String name;
|
||||
|
||||
@JsonSerialize(using = CustomLocalDateTimeSerializer.class)
|
||||
public LocalDateTime eventDate;
|
||||
|
||||
public EventWithLocalDateTime() {
|
||||
super();
|
||||
}
|
||||
|
||||
public EventWithLocalDateTime(final String name, final LocalDateTime eventDate) {
|
||||
this.name = name;
|
||||
this.eventDate = eventDate;
|
||||
}
|
||||
|
||||
public LocalDateTime getEventDate() {
|
||||
return eventDate;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package com.baeldung.jackson.date;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
|
||||
public class EventWithSerializer {
|
||||
public String name;
|
||||
|
||||
@JsonDeserialize(using = CustomDateDeserializer.class)
|
||||
@JsonSerialize(using = CustomDateSerializer.class)
|
||||
public Date eventDate;
|
||||
|
||||
public EventWithSerializer() {
|
||||
super();
|
||||
}
|
||||
|
||||
public EventWithSerializer(final String name, final Date eventDate) {
|
||||
this.name = name;
|
||||
this.eventDate = eventDate;
|
||||
}
|
||||
|
||||
public Date getEventDate() {
|
||||
return eventDate;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
}
|
||||
-64
@@ -1,64 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.jackson.entities.ClassWithAMap;
|
||||
import com.baeldung.jackson.entities.MyPair;
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class JacksonMapDeserializeUnitTest {
|
||||
|
||||
private Map<MyPair, String> map;
|
||||
private Map<MyPair, MyPair> cmap;
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@Test
|
||||
public void whenSimpleMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
|
||||
|
||||
final String jsonInput = "{\"key\": \"value\"}";
|
||||
TypeReference<HashMap<String, String>> typeRef = new TypeReference<HashMap<String, String>>() {
|
||||
};
|
||||
|
||||
final Map<String, String> map = mapper.readValue(jsonInput, typeRef);
|
||||
|
||||
Assert.assertEquals("value", map.get("key"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenObjectStringMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
|
||||
|
||||
final String jsonInput = "{\"Abbott and Costello\":\"Comedy\"}";
|
||||
|
||||
TypeReference<HashMap<MyPair, String>> typeRef = new TypeReference<HashMap<MyPair, String>>() {
|
||||
};
|
||||
|
||||
map = mapper.readValue(jsonInput, typeRef);
|
||||
|
||||
Assert.assertEquals("Comedy", map.get(new MyPair("Abbott", "Costello")));
|
||||
|
||||
ClassWithAMap classWithMap = mapper.readValue(jsonInput, ClassWithAMap.class);
|
||||
|
||||
Assert.assertEquals("Comedy", classWithMap.getMap()
|
||||
.get(new MyPair("Abbott", "Costello")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenObjectObjectMapDeserialize_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
|
||||
|
||||
final String jsonInput = "{\"Abbott and Costello\" : \"Comedy and 1940s\"}";
|
||||
TypeReference<HashMap<MyPair, MyPair>> typeRef = new TypeReference<HashMap<MyPair, MyPair>>() {
|
||||
};
|
||||
|
||||
cmap = mapper.readValue(jsonInput, typeRef);
|
||||
|
||||
Assert.assertEquals(new MyPair("Comedy", "1940s"), cmap.get(new MyPair("Abbott", "Costello")));
|
||||
}
|
||||
}
|
||||
-69
@@ -1,69 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization.dynamicobject;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Scanner;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class DynamicObjectDeserializationUnitTest {
|
||||
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
objectMapper = new ObjectMapper();
|
||||
}
|
||||
|
||||
private String readResource(String path) {
|
||||
try (Scanner scanner = new Scanner(getClass().getResourceAsStream(path), "UTF-8")) {
|
||||
return scanner.useDelimiter("\\A").next();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenJsonString_whenParsingToJsonNode_thenItMustContainDynamicProperties() throws JsonParseException, JsonMappingException, IOException {
|
||||
// given
|
||||
String json = readResource("/deserialize-dynamic-object/embedded.json");
|
||||
|
||||
// when
|
||||
ProductJsonNode product = objectMapper.readValue(json, ProductJsonNode.class);
|
||||
|
||||
// then
|
||||
assertThat(product.getName()).isEqualTo("Pear yPhone 72");
|
||||
assertThat(product.getDetails().get("audioConnector").asText()).isEqualTo("none");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenJsonString_whenParsingToMap_thenItMustContainDynamicProperties() throws JsonParseException, JsonMappingException, IOException {
|
||||
// given
|
||||
String json = readResource("/deserialize-dynamic-object/embedded.json");
|
||||
|
||||
// when
|
||||
ProductMap product = objectMapper.readValue(json, ProductMap.class);
|
||||
|
||||
// then
|
||||
assertThat(product.getName()).isEqualTo("Pear yPhone 72");
|
||||
assertThat(product.getDetails().get("audioConnector")).isEqualTo("none");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenJsonString_whenParsingWithJsonAnySetter_thenItMustContainDynamicProperties() throws JsonParseException, JsonMappingException, IOException {
|
||||
// given
|
||||
String json = readResource("/deserialize-dynamic-object/flat.json");
|
||||
|
||||
// when
|
||||
Product product = objectMapper.readValue(json, Product.class);
|
||||
|
||||
// then
|
||||
assertThat(product.getName()).isEqualTo("Pear yPhone 72");
|
||||
assertThat(product.getDetails().get("audioConnector")).isEqualTo("none");
|
||||
}
|
||||
|
||||
}
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization.enums;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import java.io.IOException;
|
||||
import org.junit.Test;
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class DefaultEnumDeserializationUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenEnum_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException {
|
||||
String json = "{\"distance\":\"KILOMETER\"}";
|
||||
City city = new ObjectMapper().readValue(json, City.class);
|
||||
|
||||
assertEquals(Distance.KILOMETER, city.getDistance());
|
||||
}
|
||||
|
||||
}
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization.enums.customdeserializer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import java.io.IOException;
|
||||
import org.junit.Test;
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class EnumCustomDeserializationUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenEnumWithCustomDeserializer_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException {
|
||||
String json = "{\"distance\": {\"unit\":\"miles\",\"meters\":1609.34}}";
|
||||
|
||||
City city = new ObjectMapper().readValue(json, City.class);
|
||||
assertEquals(Distance.MILE, city.getDistance());
|
||||
}
|
||||
}
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization.enums.jsoncreator;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import java.io.IOException;
|
||||
import org.junit.Test;
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class EnumDeserializationUsingJsonCreatorUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenEnumWithJsonCreator_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException {
|
||||
String json = "{\"distance\": {\"unit\":\"miles\",\"meters\":1609.34}}";
|
||||
|
||||
City city = new ObjectMapper().readValue(json, City.class);
|
||||
assertEquals(Distance.MILE, city.getDistance());
|
||||
}
|
||||
|
||||
}
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization.enums.jsonproperty;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import java.io.IOException;
|
||||
import org.junit.Test;
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class EnumDeserializationUsingJsonPropertyUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenEnumWithJsonProperty_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException {
|
||||
String json = "{\"distance\": \"distance-in-km\"}";
|
||||
|
||||
City city = new ObjectMapper().readValue(json, City.class);
|
||||
assertEquals(Distance.KILOMETER, city.getDistance());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization.enums.jsonvalue;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import java.io.IOException;
|
||||
import org.junit.Test;
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class EnumDeserializationUsingJsonValueUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenEnumWithJsonValue_whenDeserializingJson_thenCorrectRepresentation() throws JsonParseException, IOException {
|
||||
String json = "{\"distance\": \"0.0254\"}";
|
||||
|
||||
City city = new ObjectMapper().readValue(json, City.class);
|
||||
assertEquals(Distance.INCH, city.getDistance());
|
||||
}
|
||||
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization.immutable;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class ImmutableObjectDeserializationUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenPublicConstructorIsUsed_thenObjectIsDeserialized() throws IOException {
|
||||
final String json = "{\"name\":\"Frank\",\"id\":5000}";
|
||||
Employee employee = new ObjectMapper().readValue(json, Employee.class);
|
||||
|
||||
assertEquals("Frank", employee.getName());
|
||||
assertEquals(5000, employee.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenBuilderIsUsedAndFieldIsNull_thenObjectIsDeserialized() throws IOException {
|
||||
final String json = "{\"name\":\"Frank\"}";
|
||||
Person person = new ObjectMapper().readValue(json, Person.class);
|
||||
|
||||
assertEquals("Frank", person.getName());
|
||||
assertNull(person.getAge());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenBuilderIsUsedAndAllFieldsPresent_thenObjectIsDeserialized() throws IOException {
|
||||
final String json = "{\"name\":\"Frank\",\"age\":50}";
|
||||
Person person = new ObjectMapper().readValue(json, Person.class);
|
||||
|
||||
assertEquals("Frank", person.getName());
|
||||
assertEquals(50, (int) person.getAge());
|
||||
}
|
||||
}
|
||||
-70
@@ -1,70 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization.nested;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.module.SimpleModule;
|
||||
|
||||
public class DeserializeWithNestedPropertiesUnitTest {
|
||||
|
||||
private String SOURCE_JSON = "{\"id\":\"957c43f2-fa2e-42f9-bf75-6e3d5bb6960a\",\"name\":\"The Best Product\",\"brand\":{\"id\":\"9bcd817d-0141-42e6-8f04-e5aaab0980b6\",\"name\":\"ACME Products\",\"owner\":{\"id\":\"b21a80b1-0c09-4be3-9ebd-ea3653511c13\",\"name\":\"Ultimate Corp, Inc.\"}}}";
|
||||
|
||||
@Test
|
||||
public void whenUsingAnnotations_thenOk() throws IOException {
|
||||
Product product = new ObjectMapper().readerFor(Product.class)
|
||||
.readValue(SOURCE_JSON);
|
||||
|
||||
assertEquals(product.getName(), "The Best Product");
|
||||
assertEquals(product.getBrandName(), "ACME Products");
|
||||
assertEquals(product.getOwnerName(), "Ultimate Corp, Inc.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingJsonNode_thenOk() throws IOException {
|
||||
JsonNode productNode = new ObjectMapper().readTree(SOURCE_JSON);
|
||||
|
||||
Product product = new Product();
|
||||
product.setId(productNode.get("id")
|
||||
.textValue());
|
||||
product.setName(productNode.get("name")
|
||||
.textValue());
|
||||
product.setBrandName(productNode.get("brand")
|
||||
.get("name")
|
||||
.textValue());
|
||||
product.setOwnerName(productNode.get("brand")
|
||||
.get("owner")
|
||||
.get("name")
|
||||
.textValue());
|
||||
|
||||
assertEquals(product.getName(), "The Best Product");
|
||||
assertEquals(product.getBrandName(), "ACME Products");
|
||||
assertEquals(product.getOwnerName(), "Ultimate Corp, Inc.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingDeserializerManuallyRegistered_thenOk() throws IOException {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
SimpleModule module = new SimpleModule();
|
||||
module.addDeserializer(Product.class, new ProductDeserializer());
|
||||
mapper.registerModule(module);
|
||||
|
||||
Product product = mapper.readValue(SOURCE_JSON, Product.class);
|
||||
assertEquals(product.getName(), "The Best Product");
|
||||
assertEquals(product.getBrandName(), "ACME Products");
|
||||
assertEquals(product.getOwnerName(), "Ultimate Corp, Inc.");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingDeserializerAutoRegistered_thenOk() throws IOException {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
Product product = mapper.readValue(SOURCE_JSON, Product.class);
|
||||
assertEquals(product.getName(), "The Best Product");
|
||||
assertEquals(product.getBrandName(), "ACME Products");
|
||||
assertEquals(product.getOwnerName(), "Ultimate Corp, Inc.");
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization.nested;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
|
||||
@JsonDeserialize(using = ProductDeserializer.class)
|
||||
public class Product {
|
||||
|
||||
private String id;
|
||||
private String name;
|
||||
private String brandName;
|
||||
private String ownerName;
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getBrandName() {
|
||||
return brandName;
|
||||
}
|
||||
|
||||
public void setBrandName(String brandName) {
|
||||
this.brandName = brandName;
|
||||
}
|
||||
|
||||
public String getOwnerName() {
|
||||
return ownerName;
|
||||
}
|
||||
|
||||
public void setOwnerName(String ownerName) {
|
||||
this.ownerName = ownerName;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@JsonProperty("brand")
|
||||
private void unpackNested(Map<String, Object> brand) {
|
||||
this.brandName = (String) brand.get("name");
|
||||
Map<String, String> owner = (Map<String, String>) brand.get("owner");
|
||||
this.ownerName = owner.get("name");
|
||||
}
|
||||
}
|
||||
-40
@@ -1,40 +0,0 @@
|
||||
package com.baeldung.jackson.deserialization.nested;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
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;
|
||||
|
||||
@SuppressWarnings("serial")
|
||||
public class ProductDeserializer extends StdDeserializer<Product> {
|
||||
|
||||
public ProductDeserializer() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
public ProductDeserializer(Class<?> vc) {
|
||||
super(vc);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Product deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
|
||||
JsonNode productNode = jp.getCodec()
|
||||
.readTree(jp);
|
||||
Product product = new Product();
|
||||
product.setId(productNode.get("id")
|
||||
.textValue());
|
||||
product.setName(productNode.get("name")
|
||||
.textValue());
|
||||
product.setBrandName(productNode.get("brand")
|
||||
.get("name")
|
||||
.textValue());
|
||||
product.setOwnerName(productNode.get("brand")
|
||||
.get("owner")
|
||||
.get("name")
|
||||
.textValue());
|
||||
return product;
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package com.baeldung.jackson.dtos.ignore;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class MyDtoIgnoreType {
|
||||
|
||||
private String stringValue;
|
||||
private int intValue;
|
||||
private boolean booleanValue;
|
||||
|
||||
public MyDtoIgnoreType() {
|
||||
super();
|
||||
}
|
||||
|
||||
public MyDtoIgnoreType(final String stringValue, final int intValue, final boolean booleanValue) {
|
||||
super();
|
||||
|
||||
this.stringValue = stringValue;
|
||||
this.intValue = intValue;
|
||||
this.booleanValue = booleanValue;
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
public String getStringValue() {
|
||||
return stringValue;
|
||||
}
|
||||
|
||||
public void setStringValue(final String stringValue) {
|
||||
this.stringValue = stringValue;
|
||||
}
|
||||
|
||||
public int getIntValue() {
|
||||
return intValue;
|
||||
}
|
||||
|
||||
public void setIntValue(final int intValue) {
|
||||
this.intValue = intValue;
|
||||
}
|
||||
|
||||
public boolean isBooleanValue() {
|
||||
return booleanValue;
|
||||
}
|
||||
|
||||
public void setBooleanValue(final boolean booleanValue) {
|
||||
this.booleanValue = booleanValue;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package com.baeldung.jackson.dtos.ignore;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class MyDtoIgnoreUnknown {
|
||||
|
||||
private String stringValue;
|
||||
private int intValue;
|
||||
private boolean booleanValue;
|
||||
|
||||
public MyDtoIgnoreUnknown() {
|
||||
super();
|
||||
}
|
||||
|
||||
public MyDtoIgnoreUnknown(final String stringValue, final int intValue, final boolean booleanValue) {
|
||||
super();
|
||||
|
||||
this.stringValue = stringValue;
|
||||
this.intValue = intValue;
|
||||
this.booleanValue = booleanValue;
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
public String getStringValue() {
|
||||
return stringValue;
|
||||
}
|
||||
|
||||
public void setStringValue(final String stringValue) {
|
||||
this.stringValue = stringValue;
|
||||
}
|
||||
|
||||
public int getIntValue() {
|
||||
return intValue;
|
||||
}
|
||||
|
||||
public void setIntValue(final int intValue) {
|
||||
this.intValue = intValue;
|
||||
}
|
||||
|
||||
public boolean isBooleanValue() {
|
||||
return booleanValue;
|
||||
}
|
||||
|
||||
public void setBooleanValue(final boolean booleanValue) {
|
||||
this.booleanValue = booleanValue;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package com.baeldung.jackson.dtos.withEnum;
|
||||
|
||||
public enum DistanceEnumSimple {
|
||||
KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001);
|
||||
|
||||
private String unit;
|
||||
private final double meters;
|
||||
|
||||
private DistanceEnumSimple(String unit, double meters) {
|
||||
this.unit = unit;
|
||||
this.meters = meters;
|
||||
}
|
||||
|
||||
public double getMeters() {
|
||||
return meters;
|
||||
}
|
||||
|
||||
public String getUnit() {
|
||||
return unit;
|
||||
}
|
||||
|
||||
public void setUnit(String unit) {
|
||||
this.unit = unit;
|
||||
}
|
||||
|
||||
}
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
package com.baeldung.jackson.dtos.withEnum;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
|
||||
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
|
||||
public enum DistanceEnumWithJsonFormat {
|
||||
KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001);
|
||||
|
||||
private String unit;
|
||||
private final double meters;
|
||||
|
||||
private DistanceEnumWithJsonFormat(String unit, double meters) {
|
||||
this.unit = unit;
|
||||
this.meters = meters;
|
||||
}
|
||||
|
||||
public double getMeters() {
|
||||
return meters;
|
||||
}
|
||||
|
||||
public String getUnit() {
|
||||
return unit;
|
||||
}
|
||||
|
||||
public void setUnit(String unit) {
|
||||
this.unit = unit;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.baeldung.jackson.dtos.withEnum;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
|
||||
public enum DistanceEnumWithValue {
|
||||
KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001);
|
||||
|
||||
private String unit;
|
||||
private final double meters;
|
||||
|
||||
private DistanceEnumWithValue(String unit, double meters) {
|
||||
this.unit = unit;
|
||||
this.meters = meters;
|
||||
}
|
||||
|
||||
@JsonValue
|
||||
public double getMeters() {
|
||||
return meters;
|
||||
}
|
||||
|
||||
public String getUnit() {
|
||||
return unit;
|
||||
}
|
||||
|
||||
public void setUnit(String unit) {
|
||||
this.unit = unit;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package com.baeldung.jackson.dtos.withEnum;
|
||||
|
||||
import com.baeldung.jackson.enums.Distance;
|
||||
|
||||
public class MyDtoWithEnumCustom {
|
||||
|
||||
private String stringValue;
|
||||
private int intValue;
|
||||
private boolean booleanValue;
|
||||
private Distance type;
|
||||
|
||||
public MyDtoWithEnumCustom() {
|
||||
super();
|
||||
}
|
||||
|
||||
public MyDtoWithEnumCustom(final String stringValue, final int intValue, final boolean booleanValue, final Distance type) {
|
||||
super();
|
||||
|
||||
this.stringValue = stringValue;
|
||||
this.intValue = intValue;
|
||||
this.booleanValue = booleanValue;
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
public Distance getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(final Distance type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
package com.baeldung.jackson.dtos.withEnum;
|
||||
|
||||
public class MyDtoWithEnumJsonFormat {
|
||||
|
||||
private String stringValue;
|
||||
private int intValue;
|
||||
private boolean booleanValue;
|
||||
private DistanceEnumWithJsonFormat distanceType;
|
||||
|
||||
public MyDtoWithEnumJsonFormat() {
|
||||
super();
|
||||
}
|
||||
|
||||
public MyDtoWithEnumJsonFormat(final String stringValue, final int intValue, final boolean booleanValue, final DistanceEnumWithJsonFormat type) {
|
||||
super();
|
||||
|
||||
this.stringValue = stringValue;
|
||||
this.intValue = intValue;
|
||||
this.booleanValue = booleanValue;
|
||||
this.distanceType = type;
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
public DistanceEnumWithJsonFormat getDistanceType() {
|
||||
return distanceType;
|
||||
}
|
||||
|
||||
public void setDistanceType(final DistanceEnumWithJsonFormat type) {
|
||||
this.distanceType = type;
|
||||
}
|
||||
|
||||
}
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
package com.baeldung.jackson.enums;
|
||||
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import java.io.IOException;
|
||||
import org.junit.Test;
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class JacksonEnumSerializationUnitTest {
|
||||
|
||||
@Test
|
||||
public final void givenEnum_whenSerializingJson_thenCorrectRepresentation() throws JsonParseException, IOException {
|
||||
final String dtoAsString = new ObjectMapper().writeValueAsString(Distance.MILE);
|
||||
|
||||
assertThat(dtoAsString, containsString("1609.34"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
package com.baeldung.jackson.field;
|
||||
|
||||
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 getBooleanValue() {
|
||||
return booleanValue;
|
||||
}
|
||||
|
||||
public void setBooleanValue(final boolean booleanValue) {
|
||||
this.booleanValue = booleanValue;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.baeldung.jackson.field;
|
||||
|
||||
public class MyDtoAccessLevel {
|
||||
|
||||
private String stringValue;
|
||||
int intValue;
|
||||
protected float floatValue;
|
||||
public boolean booleanValue;
|
||||
|
||||
public MyDtoAccessLevel() {
|
||||
super();
|
||||
}
|
||||
|
||||
public MyDtoAccessLevel(final String stringValue, final int intValue, final float floatValue, final boolean booleanValue) {
|
||||
super();
|
||||
|
||||
this.stringValue = stringValue;
|
||||
this.intValue = intValue;
|
||||
this.floatValue = floatValue;
|
||||
this.booleanValue = booleanValue;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package com.baeldung.jackson.field;
|
||||
|
||||
public class MyDtoWithGetter {
|
||||
|
||||
private String stringValue;
|
||||
private int intValue;
|
||||
|
||||
public MyDtoWithGetter() {
|
||||
super();
|
||||
}
|
||||
|
||||
public MyDtoWithGetter(final String stringValue, final int intValue) {
|
||||
super();
|
||||
|
||||
this.stringValue = stringValue;
|
||||
this.intValue = intValue;
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
public String getStringValue() {
|
||||
return stringValue;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.baeldung.jackson.field;
|
||||
|
||||
public class MyDtoWithSetter {
|
||||
|
||||
private int intValue;
|
||||
public boolean booleanValue;
|
||||
|
||||
public MyDtoWithSetter() {
|
||||
super();
|
||||
}
|
||||
|
||||
public MyDtoWithSetter(final int intValue, final boolean booleanValue) {
|
||||
super();
|
||||
|
||||
this.intValue = intValue;
|
||||
this.booleanValue = booleanValue;
|
||||
}
|
||||
|
||||
// API
|
||||
|
||||
public void setIntValue(final int intValue) {
|
||||
this.intValue = intValue;
|
||||
}
|
||||
|
||||
public int accessIntValue() {
|
||||
return intValue;
|
||||
}
|
||||
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
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
@@ -0,0 +1,85 @@
|
||||
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"));
|
||||
}
|
||||
}
|
||||
}
|
||||
-66
@@ -1,66 +0,0 @@
|
||||
package com.baeldung.jackson.serialization;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.jackson.entities.MyPair;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
|
||||
import com.fasterxml.jackson.databind.ser.std.MapSerializer;
|
||||
|
||||
public class JacksonMapSerializeUnitTest {
|
||||
|
||||
@JsonSerialize(keyUsing = MyPairSerializer.class)
|
||||
private Map<MyPair, String> map;
|
||||
|
||||
@JsonSerialize(keyUsing = MapSerializer.class)
|
||||
private Map<MyPair, MyPair> cmap;
|
||||
|
||||
@JsonSerialize(keyUsing = MyPairSerializer.class)
|
||||
private MyPair mapKey;
|
||||
|
||||
@JsonSerialize(keyUsing = MyPairSerializer.class)
|
||||
private MyPair mapValue;
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@Test
|
||||
public void whenSimpleMapSerialize_thenCorrect() throws JsonProcessingException {
|
||||
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("key", "value");
|
||||
|
||||
final String jsonResult = mapper.writeValueAsString(map);
|
||||
|
||||
Assert.assertEquals("{\"key\":\"value\"}", jsonResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCustomObjectStringMapSerialize_thenCorrect() throws JsonProcessingException {
|
||||
|
||||
map = new HashMap<>();
|
||||
MyPair key = new MyPair("Abbott", "Costello");
|
||||
map.put(key, "Comedy");
|
||||
|
||||
final String jsonResult = mapper.writeValueAsString(map);
|
||||
|
||||
Assert.assertEquals("{\"Abbott and Costello\":\"Comedy\"}", jsonResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCustomObjectObjectMapSerialize_thenCorrect() throws JsonProcessingException {
|
||||
|
||||
cmap = new HashMap<>();
|
||||
mapKey = new MyPair("Abbott", "Costello");
|
||||
mapValue = new MyPair("Comedy", "1940's");
|
||||
cmap.put(mapKey, mapValue);
|
||||
|
||||
final String jsonResult = mapper.writeValueAsString(cmap);
|
||||
|
||||
Assert.assertEquals("{\"Abbott and Costello\":\"Comedy and 1940's\"}", jsonResult);
|
||||
}
|
||||
}
|
||||
-118
@@ -1,118 +0,0 @@
|
||||
package com.baeldung.jackson.streaming;
|
||||
|
||||
import com.fasterxml.jackson.core.*;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import static junit.framework.Assert.assertNull;
|
||||
import static junit.framework.Assert.assertTrue;
|
||||
import static junit.framework.TestCase.assertEquals;
|
||||
|
||||
public class JacksonStreamingAPIUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenJsonGenerator_whenAppendJsonToIt_thenGenerateJson() throws IOException {
|
||||
// given
|
||||
ByteArrayOutputStream stream = new ByteArrayOutputStream();
|
||||
JsonFactory jfactory = new JsonFactory();
|
||||
JsonGenerator jGenerator = jfactory.createGenerator(stream, JsonEncoding.UTF8);
|
||||
|
||||
// when
|
||||
jGenerator.writeStartObject();
|
||||
jGenerator.writeStringField("name", "Tom");
|
||||
jGenerator.writeNumberField("age", 25);
|
||||
jGenerator.writeFieldName("address");
|
||||
jGenerator.writeStartArray();
|
||||
jGenerator.writeString("Poland");
|
||||
jGenerator.writeString("5th avenue");
|
||||
jGenerator.writeEndArray();
|
||||
jGenerator.writeEndObject();
|
||||
jGenerator.close();
|
||||
|
||||
// then
|
||||
String json = new String(stream.toByteArray(), "UTF-8");
|
||||
assertEquals(json, "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJson_whenReadItUsingStreamAPI_thenShouldCreateProperJsonObject() throws IOException {
|
||||
// given
|
||||
String json = "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}";
|
||||
JsonFactory jfactory = new JsonFactory();
|
||||
JsonParser jParser = jfactory.createParser(json);
|
||||
|
||||
String parsedName = null;
|
||||
Integer parsedAge = null;
|
||||
List<String> addresses = new LinkedList<>();
|
||||
|
||||
// when
|
||||
while (jParser.nextToken() != JsonToken.END_OBJECT) {
|
||||
|
||||
String fieldname = jParser.getCurrentName();
|
||||
if ("name".equals(fieldname)) {
|
||||
jParser.nextToken();
|
||||
parsedName = jParser.getText();
|
||||
|
||||
}
|
||||
|
||||
if ("age".equals(fieldname)) {
|
||||
jParser.nextToken();
|
||||
parsedAge = jParser.getIntValue();
|
||||
|
||||
}
|
||||
|
||||
if ("address".equals(fieldname)) {
|
||||
jParser.nextToken();
|
||||
|
||||
while (jParser.nextToken() != JsonToken.END_ARRAY) {
|
||||
addresses.add(jParser.getText());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
jParser.close();
|
||||
|
||||
// then
|
||||
assertEquals(parsedName, "Tom");
|
||||
assertEquals(parsedAge, (Integer) 25);
|
||||
assertEquals(addresses, Arrays.asList("Poland", "5th avenue"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenJson_whenWantToExtractPartOfIt_thenShouldExtractOnlyNeededFieldWithoutGoingThroughWholeJSON() throws IOException {
|
||||
// given
|
||||
String json = "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}";
|
||||
JsonFactory jfactory = new JsonFactory();
|
||||
JsonParser jParser = jfactory.createParser(json);
|
||||
|
||||
String parsedName = null;
|
||||
Integer parsedAge = null;
|
||||
List<String> addresses = new LinkedList<>();
|
||||
|
||||
// when
|
||||
while (jParser.nextToken() != JsonToken.END_OBJECT) {
|
||||
|
||||
String fieldname = jParser.getCurrentName();
|
||||
|
||||
if ("age".equals(fieldname)) {
|
||||
jParser.nextToken();
|
||||
parsedAge = jParser.getIntValue();
|
||||
return;
|
||||
}
|
||||
|
||||
}
|
||||
jParser.close();
|
||||
|
||||
// then
|
||||
assertNull(parsedName);
|
||||
assertEquals(parsedAge, (Integer) 25);
|
||||
assertTrue(addresses.isEmpty());
|
||||
|
||||
}
|
||||
}
|
||||
-76
@@ -1,76 +0,0 @@
|
||||
package com.baeldung.jackson.test;
|
||||
|
||||
import static org.hamcrest.Matchers.instanceOf;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
|
||||
import com.baeldung.jackson.dtos.MyDto;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.type.CollectionType;
|
||||
import com.google.common.collect.Lists;
|
||||
|
||||
public class JacksonCollectionDeserializationUnitTest {
|
||||
|
||||
// tests - json to multiple entity
|
||||
|
||||
@Test
|
||||
public final void givenJsonArray_whenDeserializingAsArray_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final List<MyDto> listOfDtos = Lists.newArrayList(new MyDto("a", 1, true), new MyDto("bc", 3, false));
|
||||
final String jsonArray = mapper.writeValueAsString(listOfDtos);
|
||||
// [{"stringValue":"a","intValue":1,"booleanValue":true},{"stringValue":"bc","intValue":3,"booleanValue":false}]
|
||||
|
||||
final MyDto[] asArray = mapper.readValue(jsonArray, MyDto[].class);
|
||||
assertThat(asArray[0], instanceOf(MyDto.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenJsonArray_whenDeserializingAsListWithNoTypeInfo_thenNotCorrect() throws JsonParseException, JsonMappingException, IOException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final List<MyDto> listOfDtos = Lists.newArrayList(new MyDto("a", 1, true), new MyDto("bc", 3, false));
|
||||
final String jsonArray = mapper.writeValueAsString(listOfDtos);
|
||||
// [{"stringValue":"a","intValue":1,"booleanValue":true},{"stringValue":"bc","intValue":3,"booleanValue":false}]
|
||||
|
||||
final List<MyDto> asList = mapper.readValue(jsonArray, List.class);
|
||||
assertThat((Object) asList.get(0), instanceOf(LinkedHashMap.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenJsonArray_whenDeserializingAsListWithTypeReferenceHelp_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final List<MyDto> listOfDtos = Lists.newArrayList(new MyDto("a", 1, true), new MyDto("bc", 3, false));
|
||||
final String jsonArray = mapper.writeValueAsString(listOfDtos);
|
||||
// [{"stringValue":"a","intValue":1,"booleanValue":true},{"stringValue":"bc","intValue":3,"booleanValue":false}]
|
||||
|
||||
final List<MyDto> asList = mapper.readValue(jsonArray, new TypeReference<List<MyDto>>() {
|
||||
});
|
||||
assertThat(asList.get(0), instanceOf(MyDto.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenJsonArray_whenDeserializingAsListWithJavaTypeHelp_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final List<MyDto> listOfDtos = Lists.newArrayList(new MyDto("a", 1, true), new MyDto("bc", 3, false));
|
||||
final String jsonArray = mapper.writeValueAsString(listOfDtos);
|
||||
// [{"stringValue":"a","intValue":1,"booleanValue":true},{"stringValue":"bc","intValue":3,"booleanValue":false}]
|
||||
|
||||
final CollectionType javaType = mapper.getTypeFactory()
|
||||
.constructCollectionType(List.class, MyDto.class);
|
||||
final List<MyDto> asList = mapper.readValue(jsonArray, javaType);
|
||||
assertThat(asList.get(0), instanceOf(MyDto.class));
|
||||
}
|
||||
|
||||
}
|
||||
// a (private) no-args constructor is required (simulate without)
|
||||
@@ -1,176 +0,0 @@
|
||||
package com.baeldung.jackson.test;
|
||||
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.joda.time.DateTime;
|
||||
import org.joda.time.DateTimeZone;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.jackson.date.Event;
|
||||
import com.baeldung.jackson.date.EventWithFormat;
|
||||
import com.baeldung.jackson.date.EventWithJodaTime;
|
||||
import com.baeldung.jackson.date.EventWithLocalDateTime;
|
||||
import com.baeldung.jackson.date.EventWithSerializer;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.databind.util.StdDateFormat;
|
||||
import com.fasterxml.jackson.datatype.joda.JodaModule;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
|
||||
public class JacksonDateUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenSerializingDateWithJackson_thenSerializedToNumber() throws JsonProcessingException, ParseException {
|
||||
final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm");
|
||||
df.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||
|
||||
final String toParse = "01-01-1970 01:00";
|
||||
final Date date = df.parse(toParse);
|
||||
final Event event = new Event("party", date);
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final String result = mapper.writeValueAsString(event);
|
||||
assertThat(result, containsString("3600000"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSerializingDateToISO8601_thenSerializedToText() throws JsonProcessingException, ParseException {
|
||||
final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm");
|
||||
df.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||
|
||||
final String toParse = "01-01-1970 02:30";
|
||||
final Date date = df.parse(toParse);
|
||||
final Event event = new Event("party", date);
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
|
||||
// StdDateFormat is ISO8601 since jackson 2.9
|
||||
mapper.setDateFormat(new StdDateFormat().withColonInTimeZone(true));
|
||||
|
||||
final String result = mapper.writeValueAsString(event);
|
||||
assertThat(result, containsString("1970-01-01T02:30:00.000+00:00"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSettingObjectMapperDateFormat_thenCorrect() throws JsonProcessingException, ParseException {
|
||||
final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm");
|
||||
|
||||
final String toParse = "20-12-2014 02:30";
|
||||
final Date date = df.parse(toParse);
|
||||
final Event event = new Event("party", date);
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.setDateFormat(df);
|
||||
|
||||
final String result = mapper.writeValueAsString(event);
|
||||
assertThat(result, containsString(toParse));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingJsonFormatAnnotationToFormatDate_thenCorrect() throws JsonProcessingException, ParseException {
|
||||
final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
|
||||
df.setTimeZone(TimeZone.getTimeZone("UTC"));
|
||||
|
||||
final String toParse = "20-12-2014 02:30:00";
|
||||
final Date date = df.parse(toParse);
|
||||
final EventWithFormat event = new EventWithFormat("party", date);
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final String result = mapper.writeValueAsString(event);
|
||||
assertThat(result, containsString(toParse));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCustomDateSerializer_thenCorrect() throws JsonProcessingException, ParseException {
|
||||
final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
|
||||
|
||||
final String toParse = "20-12-2014 02:30:00";
|
||||
final Date date = df.parse(toParse);
|
||||
final EventWithSerializer event = new EventWithSerializer("party", date);
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final String result = mapper.writeValueAsString(event);
|
||||
assertThat(result, containsString(toParse));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSerializingJodaTimeWithJackson_thenCorrect() throws JsonProcessingException {
|
||||
final DateTime date = new DateTime(2014, 12, 20, 2, 30);
|
||||
final EventWithJodaTime event = new EventWithJodaTime("party", date);
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final String result = mapper.writeValueAsString(event);
|
||||
assertThat(result, containsString("2014-12-20 02:30"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSerializingJava8DateWithCustomSerializer_thenCorrect() throws JsonProcessingException {
|
||||
final LocalDateTime date = LocalDateTime.of(2014, 12, 20, 2, 30);
|
||||
final EventWithLocalDateTime event = new EventWithLocalDateTime("party", date);
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final String result = mapper.writeValueAsString(event);
|
||||
assertThat(result, containsString("2014-12-20 02:30"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDeserializingDateWithJackson_thenCorrect() throws JsonProcessingException, IOException {
|
||||
final String json = "{\"name\":\"party\",\"eventDate\":\"20-12-2014 02:30:00\"}";
|
||||
|
||||
final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.setDateFormat(df);
|
||||
|
||||
final Event event = mapper.readerFor(Event.class)
|
||||
.readValue(json);
|
||||
assertEquals("20-12-2014 02:30:00", df.format(event.eventDate));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDeserializingDateUsingCustomDeserializer_thenCorrect() throws JsonProcessingException, IOException {
|
||||
final String json = "{\"name\":\"party\",\"eventDate\":\"20-12-2014 02:30:00\"}";
|
||||
|
||||
final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final EventWithSerializer event = mapper.readerFor(EventWithSerializer.class)
|
||||
.readValue(json);
|
||||
assertEquals("20-12-2014 02:30:00", df.format(event.eventDate));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSerializingJava8Date_thenCorrect() throws JsonProcessingException {
|
||||
final LocalDateTime date = LocalDateTime.of(2014, 12, 20, 2, 30);
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.registerModule(new JavaTimeModule());
|
||||
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
|
||||
final String result = mapper.writeValueAsString(date);
|
||||
assertThat(result, containsString("2014-12-20T02:30"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSerializingJodaTime_thenCorrect() throws JsonProcessingException {
|
||||
final DateTime date = new DateTime(2014, 12, 20, 2, 30, DateTimeZone.forID("Europe/London"));
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.registerModule(new JodaModule());
|
||||
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
|
||||
final String result = mapper.writeValueAsString(date);
|
||||
assertThat(result, containsString("2014-12-20T02:30:00.000Z"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -17,7 +17,6 @@ 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.baeldung.jackson.dtos.ignore.MyDtoIgnoreUnknown;
|
||||
import com.fasterxml.jackson.core.JsonFactory;
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
@@ -54,91 +53,6 @@ public class JacksonDeserializationUnitTest {
|
||||
assertThat(readValue.isBooleanValue(), equalTo(true));
|
||||
}
|
||||
|
||||
// tests - json with unknown fields
|
||||
|
||||
@Test(expected = UnrecognizedPropertyException.class)
|
||||
public final void givenJsonHasUnknownValues_whenDeserializingAJsonToAClass_thenExceptionIsThrown() throws JsonParseException, JsonMappingException, IOException {
|
||||
final String jsonAsString = "{\"stringValue\":\"a\",\"intValue\":1,\"booleanValue\":true,\"stringValue2\":\"something\"}";
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final MyDto readValue = mapper.readValue(jsonAsString, MyDto.class);
|
||||
|
||||
assertNotNull(readValue);
|
||||
assertThat(readValue.getStringValue(), equalTo("a"));
|
||||
assertThat(readValue.isBooleanValue(), equalTo(true));
|
||||
assertThat(readValue.getIntValue(), equalTo(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenJsonHasUnknownValuesButJacksonIsIgnoringUnknownFields_whenDeserializing_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
|
||||
final String jsonAsString = // @formatter:off
|
||||
"{\"stringValue\":\"a\"," +
|
||||
"\"intValue\":1," +
|
||||
"\"booleanValue\":true," +
|
||||
"\"stringValue2\":\"something\"}"; // @formatter:on
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
|
||||
final MyDto readValue = mapper.readValue(jsonAsString, MyDto.class);
|
||||
|
||||
assertNotNull(readValue);
|
||||
assertThat(readValue.getStringValue(), equalTo("a"));
|
||||
assertThat(readValue.isBooleanValue(), equalTo(true));
|
||||
assertThat(readValue.getIntValue(), equalTo(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenJsonHasUnknownValuesButUnknownFieldsAreIgnoredOnClass_whenDeserializing_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
|
||||
final String jsonAsString = // @formatter:off
|
||||
"{\"stringValue\":\"a\"," +
|
||||
"\"intValue\":1," +
|
||||
"\"booleanValue\":true," +
|
||||
"\"stringValue2\":\"something\"}"; // @formatter:on
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final MyDtoIgnoreUnknown readValue = mapper.readValue(jsonAsString, MyDtoIgnoreUnknown.class);
|
||||
|
||||
assertNotNull(readValue);
|
||||
assertThat(readValue.getStringValue(), equalTo("a"));
|
||||
assertThat(readValue.isBooleanValue(), equalTo(true));
|
||||
assertThat(readValue.getIntValue(), equalTo(1));
|
||||
}
|
||||
|
||||
// to JsonNode
|
||||
|
||||
@Test
|
||||
public final void whenParsingJsonStringIntoJsonNode_thenCorrect() throws JsonParseException, IOException {
|
||||
final String jsonString = "{\"k1\":\"v1\",\"k2\":\"v2\"}";
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final JsonNode actualObj = mapper.readTree(jsonString);
|
||||
|
||||
assertNotNull(actualObj);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenUsingLowLevelDetails_whenParsingJsonStringIntoJsonNode_thenCorrect() throws JsonParseException, IOException {
|
||||
final String jsonString = "{\"k1\":\"v1\",\"k2\":\"v2\"}";
|
||||
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final JsonFactory factory = mapper.getFactory();
|
||||
final JsonParser parser = factory.createParser(jsonString);
|
||||
final JsonNode actualObj = mapper.readTree(parser);
|
||||
|
||||
assertNotNull(actualObj);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenTheJsonNode_whenRetrievingDataFromId_thenCorrect() throws JsonParseException, IOException {
|
||||
final String jsonString = "{\"k1\":\"v1\",\"k2\":\"v2\"}";
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final JsonNode actualObj = mapper.readTree(jsonString);
|
||||
|
||||
// When
|
||||
final JsonNode jsonNode1 = actualObj.get("k1");
|
||||
assertThat(jsonNode1.textValue(), equalTo("v1"));
|
||||
}
|
||||
|
||||
// custom deserialization
|
||||
|
||||
@Test
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
package com.baeldung.jackson.test;
|
||||
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import com.baeldung.jackson.field.MyDtoAccessLevel;
|
||||
import com.baeldung.jackson.field.MyDtoWithSetter;
|
||||
import com.baeldung.jackson.field.MyDtoWithGetter;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
|
||||
import com.fasterxml.jackson.annotation.PropertyAccessor;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class JacksonFieldUnitTest {
|
||||
|
||||
@Test
|
||||
public final void givenDifferentAccessLevels_whenPublic_thenSerializable() throws JsonProcessingException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final MyDtoAccessLevel dtoObject = new MyDtoAccessLevel();
|
||||
|
||||
final String dtoAsString = mapper.writeValueAsString(dtoObject);
|
||||
assertThat(dtoAsString, not(containsString("stringValue")));
|
||||
assertThat(dtoAsString, not(containsString("intValue")));
|
||||
assertThat(dtoAsString, not(containsString("floatValue")));
|
||||
assertThat(dtoAsString, containsString("booleanValue"));
|
||||
System.out.println(dtoAsString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenDifferentAccessLevels_whenGetterAdded_thenSerializable() throws JsonProcessingException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final MyDtoWithGetter dtoObject = new MyDtoWithGetter();
|
||||
|
||||
final String dtoAsString = mapper.writeValueAsString(dtoObject);
|
||||
assertThat(dtoAsString, containsString("stringValue"));
|
||||
assertThat(dtoAsString, not(containsString("intValue")));
|
||||
System.out.println(dtoAsString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenDifferentAccessLevels_whenGetterAdded_thenDeserializable() throws IOException {
|
||||
final String jsonAsString = "{\"stringValue\":\"dtoString\"}";
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final MyDtoWithGetter dtoObject = mapper.readValue(jsonAsString, MyDtoWithGetter.class);
|
||||
|
||||
assertNotNull(dtoObject);
|
||||
assertThat(dtoObject.getStringValue(), equalTo("dtoString"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenDifferentAccessLevels_whenSetterAdded_thenDeserializable() throws IOException {
|
||||
final String jsonAsString = "{\"intValue\":1}";
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final MyDtoWithSetter dtoObject = mapper.readValue(jsonAsString, MyDtoWithSetter.class);
|
||||
|
||||
assertNotNull(dtoObject);
|
||||
assertThat(dtoObject.accessIntValue(), equalTo(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenDifferentAccessLevels_whenSetterAdded_thenStillNotSerializable() throws IOException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
final MyDtoWithSetter dtoObject = new MyDtoWithSetter();
|
||||
|
||||
final String dtoAsString = mapper.writeValueAsString(dtoObject);
|
||||
assertThat(dtoAsString, not(containsString("intValue")));
|
||||
System.out.println(dtoAsString);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenDifferentAccessLevels_whenSetVisibility_thenSerializable() throws IOException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
|
||||
|
||||
final MyDtoAccessLevel dtoObject = new MyDtoAccessLevel();
|
||||
|
||||
final String dtoAsString = mapper.writeValueAsString(dtoObject);
|
||||
assertThat(dtoAsString, containsString("stringValue"));
|
||||
assertThat(dtoAsString, containsString("intValue"));
|
||||
assertThat(dtoAsString, containsString("booleanValue"));
|
||||
System.out.println(dtoAsString);
|
||||
}
|
||||
|
||||
}
|
||||
-78
@@ -1,78 +0,0 @@
|
||||
package com.baeldung.jackson.test;
|
||||
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.jackson.dtos.withEnum.DistanceEnumSimple;
|
||||
import com.baeldung.jackson.dtos.withEnum.DistanceEnumWithJsonFormat;
|
||||
import com.baeldung.jackson.dtos.withEnum.DistanceEnumWithValue;
|
||||
import com.baeldung.jackson.dtos.withEnum.MyDtoWithEnumCustom;
|
||||
import com.baeldung.jackson.dtos.withEnum.MyDtoWithEnumJsonFormat;
|
||||
import com.baeldung.jackson.enums.Distance;
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class JacksonSerializationEnumsUnitTest {
|
||||
|
||||
// tests - simple enum
|
||||
|
||||
@Test
|
||||
public final void whenSerializingASimpleEnum_thenCorrect() throws JsonParseException, IOException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final String enumAsString = mapper.writeValueAsString(DistanceEnumSimple.MILE);
|
||||
|
||||
assertThat(enumAsString, containsString("MILE"));
|
||||
}
|
||||
|
||||
// tests - enum with main value
|
||||
|
||||
@Test
|
||||
public final void whenSerializingAEnumWithValue_thenCorrect() throws JsonParseException, IOException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final String enumAsString = mapper.writeValueAsString(DistanceEnumWithValue.MILE);
|
||||
|
||||
assertThat(enumAsString, is("1609.34"));
|
||||
}
|
||||
|
||||
// tests - enum
|
||||
|
||||
@Test
|
||||
public final void whenSerializingAnEnum_thenCorrect() throws JsonParseException, IOException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final String enumAsString = mapper.writeValueAsString(DistanceEnumWithJsonFormat.MILE);
|
||||
|
||||
assertThat(enumAsString, containsString("\"meters\":1609.34"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenSerializingEntityWithEnum_thenCorrect() throws JsonParseException, IOException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final String enumAsString = mapper.writeValueAsString(new MyDtoWithEnumJsonFormat("a", 1, true, DistanceEnumWithJsonFormat.MILE));
|
||||
|
||||
assertThat(enumAsString, containsString("\"meters\":1609.34"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenSerializingArrayOfEnums_thenCorrect() throws JsonParseException, IOException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final String json = mapper.writeValueAsString(new DistanceEnumWithJsonFormat[] { DistanceEnumWithJsonFormat.MILE, DistanceEnumWithJsonFormat.KILOMETER });
|
||||
|
||||
assertThat(json, containsString("\"meters\":1609.34"));
|
||||
}
|
||||
|
||||
// tests - enum with custom serializer
|
||||
|
||||
@Test
|
||||
public final void givenCustomSerializer_whenSerializingEntityWithEnum_thenCorrect() throws JsonParseException, IOException {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final String enumAsString = mapper.writeValueAsString(new MyDtoWithEnumCustom("a", 1, true, Distance.MILE));
|
||||
|
||||
assertThat(enumAsString, containsString("\"meters\":1609.34"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -7,13 +7,10 @@ import org.junit.runners.Suite;
|
||||
|
||||
@RunWith(Suite.class)
|
||||
@Suite.SuiteClasses({ // @formatter:off
|
||||
JacksonCollectionDeserializationUnitTest.class
|
||||
,JacksonSerializationEnumsUnitTest.class
|
||||
,JacksonDeserializationUnitTest.class
|
||||
JacksonDeserializationUnitTest.class
|
||||
,JacksonDeserializationUnitTest.class
|
||||
,JacksonPrettyPrintUnitTest.class
|
||||
,SandboxUnitTest.class
|
||||
,JacksonFieldUnitTest.class
|
||||
}) // @formatter:on
|
||||
public class UnitTestSuite {
|
||||
}
|
||||
@@ -1,184 +0,0 @@
|
||||
package com.baeldung.jackson.xml;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.jackson.dtos.Address;
|
||||
import com.baeldung.jackson.dtos.Person;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
|
||||
|
||||
public class XMLSerializeDeserializeUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenJavaSerializedToXmlStr_thenCorrect() throws JsonProcessingException {
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
String xml = xmlMapper.writeValueAsString(new SimpleBean());
|
||||
assertNotNull(xml);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJavaSerializedToXmlFile_thenCorrect() throws IOException {
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
xmlMapper.writeValue(new File("target/simple_bean.xml"), new SimpleBean());
|
||||
File file = new File("target/simple_bean.xml");
|
||||
assertNotNull(file);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJavaGotFromXmlStr_thenCorrect() throws IOException {
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
SimpleBean value = xmlMapper.readValue("<SimpleBean><x>1</x><y>2</y></SimpleBean>", SimpleBean.class);
|
||||
assertTrue(value.getX() == 1 && value.getY() == 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJavaGotFromXmlFile_thenCorrect() throws IOException {
|
||||
File file = new File("src/test/resources/simple_bean.xml");
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
String xml = inputStreamToString(new FileInputStream(file));
|
||||
SimpleBean value = xmlMapper.readValue(xml, SimpleBean.class);
|
||||
assertTrue(value.getX() == 1 && value.getY() == 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJavaGotFromXmlStrWithCapitalElem_thenCorrect() throws IOException {
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
SimpleBeanForCapitalizedFields value = xmlMapper.readValue("<SimpleBeanForCapitalizedFields><X>1</X><y>2</y></SimpleBeanForCapitalizedFields>", SimpleBeanForCapitalizedFields.class);
|
||||
assertTrue(value.getX() == 1 && value.getY() == 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJavaSerializedToXmlFileWithCapitalizedField_thenCorrect() throws IOException {
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
xmlMapper.writeValue(new File("target/simple_bean_capitalized.xml"), new SimpleBeanForCapitalizedFields());
|
||||
File file = new File("target/simple_bean_capitalized.xml");
|
||||
assertNotNull(file);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJavaDeserializedFromXmlFile_thenCorrect() throws IOException {
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
|
||||
String xml = "<person><firstName>Rohan</firstName><lastName>Daye</lastName><phoneNumbers><phoneNumbers>9911034731</phoneNumbers><phoneNumbers>9911033478</phoneNumbers></phoneNumbers><address><address><streetNumber>1</streetNumber><streetName>Name1</streetName><city>City1</city></address><address><streetNumber>2</streetNumber><streetName>Name2</streetName><city>City2</city></address></address></person>";
|
||||
Person value = xmlMapper.readValue(xml, Person.class);
|
||||
|
||||
assertTrue(value.getAddress()
|
||||
.get(0)
|
||||
.getCity()
|
||||
.equalsIgnoreCase("city1")
|
||||
&& value.getAddress()
|
||||
.get(1)
|
||||
.getCity()
|
||||
.equalsIgnoreCase("city2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJavaSerializedToXmlFile_thenSuccess() throws IOException {
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
|
||||
String expectedXml = "<person><firstName>Rohan</firstName><lastName>Daye</lastName><phoneNumbers><phoneNumbers>9911034731</phoneNumbers><phoneNumbers>9911033478</phoneNumbers></phoneNumbers><address><address><streetNumber>1</streetNumber><streetName>Name1</streetName><city>City1</city></address><address><streetNumber>2</streetNumber><streetName>Name2</streetName><city>City2</city></address></address></person>";
|
||||
|
||||
Person person = new Person();
|
||||
|
||||
person.setFirstName("Rohan");
|
||||
person.setLastName("Daye");
|
||||
|
||||
List<String> ph = new ArrayList<>();
|
||||
ph.add("9911034731");
|
||||
ph.add("9911033478");
|
||||
person.setPhoneNumbers(ph);
|
||||
|
||||
List<Address> addresses = new ArrayList<>();
|
||||
|
||||
Address address1 = new Address();
|
||||
address1.setStreetNumber("1");
|
||||
address1.setStreetName("Name1");
|
||||
address1.setCity("City1");
|
||||
|
||||
Address address2 = new Address();
|
||||
address2.setStreetNumber("2");
|
||||
address2.setStreetName("Name2");
|
||||
address2.setCity("City2");
|
||||
|
||||
addresses.add(address1);
|
||||
addresses.add(address2);
|
||||
|
||||
person.setAddress(addresses);
|
||||
|
||||
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
|
||||
xmlMapper.writeValue(byteArrayOutputStream, person);
|
||||
assertEquals(expectedXml, byteArrayOutputStream.toString());
|
||||
}
|
||||
|
||||
private static String inputStreamToString(InputStream is) throws IOException {
|
||||
BufferedReader br;
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
String line;
|
||||
br = new BufferedReader(new InputStreamReader(is));
|
||||
while ((line = br.readLine()) != null) {
|
||||
sb.append(line);
|
||||
}
|
||||
br.close();
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
||||
class SimpleBean {
|
||||
private int x = 1;
|
||||
private int y = 2;
|
||||
|
||||
public int getX() {
|
||||
return x;
|
||||
}
|
||||
|
||||
public void setX(int x) {
|
||||
this.x = x;
|
||||
}
|
||||
|
||||
public int getY() {
|
||||
return y;
|
||||
}
|
||||
|
||||
public void setY(int y) {
|
||||
this.y = y;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class SimpleBeanForCapitalizedFields {
|
||||
@JsonProperty("X")
|
||||
private int x = 1;
|
||||
private int y = 2;
|
||||
|
||||
public int getX() {
|
||||
return x;
|
||||
}
|
||||
|
||||
public void setX(int x) {
|
||||
this.x = x;
|
||||
}
|
||||
|
||||
public int getY() {
|
||||
return y;
|
||||
}
|
||||
|
||||
public void setY(int y) {
|
||||
this.y = y;
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
package com.baeldung.jackson.xmlToJson;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class XmlToJsonUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenAnXML_whenUseDataBidingToConvertToJSON_thenReturnDataOK() throws IOException{
|
||||
String flowerXML = "<Flower><name>Poppy</name><color>RED</color><petals>9</petals></Flower>";
|
||||
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
Flower poppy = xmlMapper.readValue(flowerXML, Flower.class);
|
||||
|
||||
assertEquals(poppy.getName(), "Poppy");
|
||||
assertEquals(poppy.getColor(), Color.RED);
|
||||
assertEquals(poppy.getPetals(), new Integer(9));
|
||||
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
String json = mapper.writeValueAsString(poppy);
|
||||
|
||||
assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":9}");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnXML_whenUseATreeConvertToJSON_thenReturnDataOK() throws IOException {
|
||||
String flowerXML = "<Flower><name>Poppy</name><color>RED</color><petals>9</petals></Flower>";
|
||||
|
||||
XmlMapper xmlMapper = new XmlMapper();
|
||||
JsonNode node = xmlMapper.readTree(flowerXML.getBytes());
|
||||
|
||||
ObjectMapper jsonMapper = new ObjectMapper();
|
||||
String json = jsonMapper.writeValueAsString(node);
|
||||
|
||||
assertEquals(json, "{\"name\":\"Poppy\",\"color\":\"RED\",\"petals\":\"9\"}");
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
{
|
||||
"name": "Pear yPhone 72",
|
||||
"category": "cellphone",
|
||||
"details": {
|
||||
"displayAspectRatio": "97:3",
|
||||
"audioConnector": "none"
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"name": "Pear yPhone 72",
|
||||
"category": "cellphone",
|
||||
"displayAspectRatio": "97:3",
|
||||
"audioConnector": "none"
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"color": "Black",
|
||||
"type": "BMW"
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
<SimpleBean>
|
||||
<x>1</x>
|
||||
<y>2</y>
|
||||
</SimpleBean>
|
||||
Reference in New Issue
Block a user