BAEL-19947: Migrate gson module to the com.baeldung package

This commit is contained in:
Krzysiek
2019-12-15 21:16:48 +01:00
parent 4a46ad8991
commit a73d7872b5
55 changed files with 144 additions and 147 deletions
@@ -0,0 +1,57 @@
package com.baeldung.gson.entities;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
public class ActorGson {
private String imdbId;
private Date dateOfBirth;
private List<String> filmography;
public ActorGson(String imdbId, Date dateOfBirth, List<String> filmography) {
super();
this.imdbId = imdbId;
this.dateOfBirth = dateOfBirth;
this.filmography = filmography;
}
@Override
public String toString() {
return "ActorGson [imdbId=" + imdbId + ", dateOfBirth=" + formatDateOfBirth() + ", filmography=" + filmography + "]";
}
public String getImdbId() {
return imdbId;
}
public void setImdbId(String imdbId) {
this.imdbId = imdbId;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public List<String> getFilmography() {
return filmography;
}
public void setFilmography(List<String> filmography) {
this.filmography = filmography;
}
private String formatDateOfBirth() {
final DateFormat formatter = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy");
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
return formatter.format(dateOfBirth);
}
}
@@ -0,0 +1,5 @@
package com.baeldung.gson.entities;
public abstract class Animal {
public String type = "Animal";
}
@@ -0,0 +1,19 @@
package com.baeldung.gson.entities;
public class Cow extends Animal {
private String breed;
public Cow() {
breed = "Jersey";
type = "Cow";
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
}
@@ -0,0 +1,18 @@
package com.baeldung.gson.entities;
public class Dog extends Animal {
private String petName;
public Dog() {
petName = "Milo";
type = "Dog";
}
public String getPetName() {
return petName;
}
public void setPetName(String petName) {
this.petName = petName;
}
}
@@ -0,0 +1,36 @@
package com.baeldung.gson.entities;
public class Employee {
private int id;
private String name;
private String address;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
@@ -0,0 +1,48 @@
package com.baeldung.gson.entities;
import java.util.List;
public class Movie {
private String imdbId;
private String director;
private List<ActorGson> actors;
public Movie(String imdbID, String director, List<ActorGson> actors) {
super();
this.imdbId = imdbID;
this.director = director;
this.actors = actors;
}
@Override
public String toString() {
return "Movie [imdbId=" + imdbId + ", director=" + director + ", actors=" + actors + "]";
}
public String getImdbID() {
return imdbId;
}
public void setImdbID(String imdbID) {
this.imdbId = imdbID;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public List<ActorGson> getActors() {
return actors;
}
public void setActors(List<ActorGson> actors) {
this.actors = actors;
}
}
@@ -0,0 +1,46 @@
package com.baeldung.gson.entities;
import com.google.gson.annotations.Expose;
import java.util.List;
public class MovieWithNullValue {
@Expose
private String imdbId;
private String director;
@Expose
private List<ActorGson> actors;
public MovieWithNullValue(String imdbID, String director, List<ActorGson> actors) {
super();
this.imdbId = imdbID;
this.director = director;
this.actors = actors;
}
public String getImdbID() {
return imdbId;
}
public void setImdbID(String imdbID) {
this.imdbId = imdbID;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public List<ActorGson> getActors() {
return actors;
}
public void setActors(List<ActorGson> actors) {
this.actors = actors;
}
}
@@ -0,0 +1,49 @@
package com.baeldung.gson.entities;
import java.util.Objects;
public class MyClass {
private int id;
private String name;
public MyClass(int id, String name) {
this.id = id;
this.name = name;
}
public MyClass() { }
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MyClass myClass = (MyClass) o;
return id == myClass.id && Objects.equals(name, myClass.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
}
@@ -0,0 +1,19 @@
package com.baeldung.gson.entities;
public class User {
private int id;
private String name;
private transient String nationality;
public User(int id, String name, String nationality) {
this.id = id;
this.name = name;
this.nationality = nationality;
}
public User(int id, String name) {
this(id, name, null);
}
}
@@ -0,0 +1,40 @@
package com.baeldung.gson.entities;
import com.google.gson.annotations.SerializedName;
public class Weather {
@SerializedName(value = "location", alternate = "place")
private String location;
@SerializedName(value = "temp", alternate = "temperature")
private int temp;
@SerializedName(value = "outlook", alternate = "weather")
private String outlook;
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getTemp() {
return temp;
}
public void setTemp(int temp) {
this.temp = temp;
}
public String getOutlook() {
return outlook;
}
public void setOutlook(String outlook) {
this.outlook = outlook;
}
}
@@ -0,0 +1,9 @@
package com.baeldung.gson.primitives.models;
public class BooleanExample {
public boolean value;
public String toString() {
return "{boolean: " + value + "}";
}
}
@@ -0,0 +1,9 @@
package com.baeldung.gson.primitives.models;
public class ByteExample {
public byte value = (byte) 1;
public String toString() {
return "{byte: " + value + "}";
}
}
@@ -0,0 +1,9 @@
package com.baeldung.gson.primitives.models;
public class CharExample {
public char value;
public String toString() {
return "{char: " + value + "}";
}
}
@@ -0,0 +1,9 @@
package com.baeldung.gson.primitives.models;
public class DoubleExample {
public double value;
public String toString() {
return "{float: " + value + "}";
}
}
@@ -0,0 +1,9 @@
package com.baeldung.gson.primitives.models;
public class FloatExample {
public float value;
public String toString() {
return "{float: " + value + "}";
}
}
@@ -0,0 +1,6 @@
package com.baeldung.gson.primitives.models;
public class InfinityValuesExample {
public float negativeInfinity;
public float positiveInfinity;
}
@@ -0,0 +1,9 @@
package com.baeldung.gson.primitives.models;
public class LongExample {
public long value = 1;
public String toString() {
return "{byte: " + value + "}";
}
}
@@ -0,0 +1,19 @@
package com.baeldung.gson.primitives.models;
public class PrimitiveBundle {
public byte byteValue;
public short shortValue;
public int intValue;
public long longValue;
public float floatValue;
public double doubleValue;
public boolean booleanValue;
public char charValue;
public String toString() {
return "{" + "byte: " + byteValue + ", " + "short: " + shortValue + ", "
+ "int: " + intValue + ", " + "long: " + longValue + ", "
+ "float: " + floatValue + ", " + "double: " + doubleValue + ", "
+ "boolean: " + booleanValue + ", " + "char: " + charValue + "}";
}
}
@@ -0,0 +1,18 @@
package com.baeldung.gson.primitives.models;
public class PrimitiveBundleInitialized {
// @formatter:off
public byte byteValue = (byte) 1;
public short shortValue = (short) 1;
public int intValue = 1;
public long longValue = 1L;
public float floatValue = 1.0f;
public double doubleValue = 1;
// @formatter:on
public String toString() {
return "{" + "byte: " + byteValue + ", " + "short: " + shortValue + ", "
+ "int: " + intValue + ", " + "long: " + longValue + ", "
+ "float: " + floatValue + ", " + "double: " + doubleValue + "}";
}
}
@@ -0,0 +1,46 @@
package com.baeldung.gson.serialization;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import com.baeldung.gson.entities.ActorGson;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
public class ActorGsonDeserializer implements JsonDeserializer<ActorGson> {
private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
@Override
public ActorGson deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
final JsonObject jsonObject = json.getAsJsonObject();
final JsonElement jsonImdbId = jsonObject.get("imdbId");
final JsonElement jsonDateOfBirth = jsonObject.get("dateOfBirth");
final JsonArray jsonFilmography = jsonObject.getAsJsonArray("filmography");
final ArrayList<String> filmList = new ArrayList<String>();
if (jsonFilmography != null) {
for (int i = 0; i < jsonFilmography.size(); i++) {
filmList.add(jsonFilmography.get(i).getAsString());
}
}
ActorGson actorGson = null;
try {
actorGson = new ActorGson(jsonImdbId.getAsString(), sdf.parse(jsonDateOfBirth.getAsString()), filmList);
} catch (final ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return actorGson;
}
}
@@ -0,0 +1,33 @@
package com.baeldung.gson.serialization;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.baeldung.gson.entities.ActorGson;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.stream.Collectors;
public class ActorGsonSerializer implements JsonSerializer<ActorGson> {
private SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
@Override
public JsonElement serialize(ActorGson actor, Type type, JsonSerializationContext jsonSerializationContext) {
JsonObject actorJsonObj = new JsonObject();
actorJsonObj.addProperty("<strong>IMDB Code</strong>", actor.getImdbId());
actorJsonObj.addProperty("<strong>Date Of Birth</strong>", actor.getDateOfBirth() != null ? sdf.format(actor.getDateOfBirth()) : null);
actorJsonObj.addProperty("<strong>N° Film:</strong> ", actor.getFilmography() != null ? actor.getFilmography().size() : null);
actorJsonObj.addProperty("filmography", actor.getFilmography() != null ? convertFilmography(actor.getFilmography()) : null);
return actorJsonObj;
}
private String convertFilmography(List<String> filmography) {
return filmography.stream().collect(Collectors.joining("-"));
}
}
@@ -0,0 +1,35 @@
package com.baeldung.gson.serialization;
import com.google.gson.Gson;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import com.baeldung.gson.entities.Animal;
public class AnimalDeserializer implements JsonDeserializer<Animal> {
private String animalTypeElementName;
private Gson gson;
private Map<String, Class<? extends Animal>> animalTypeRegistry;
public AnimalDeserializer(String animalTypeElementName) {
this.animalTypeElementName = animalTypeElementName;
this.gson = new Gson();
this.animalTypeRegistry = new HashMap<>();
}
public void registerBarnType(String animalTypeName, Class<? extends Animal> animalType) {
animalTypeRegistry.put(animalTypeName, animalType);
}
public Animal deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
JsonObject animalObject = json.getAsJsonObject();
JsonElement animalTypeElement = animalObject.get(animalTypeElementName);
Class<? extends Animal> animalType = animalTypeRegistry.get(animalTypeElement.getAsString());
return gson.fromJson(animalObject, animalType);
}
}
@@ -0,0 +1,63 @@
package com.baeldung.gson.serialization;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.Map;
import java.util.stream.Collectors;
import com.baeldung.gson.entities.Employee;
import com.google.gson.*;
public class MapDeserializer implements JsonDeserializer<Map<String, Object>> {
@Override
public Map<String, Object> deserialize(JsonElement elem, Type type, JsonDeserializationContext context) throws JsonParseException {
return elem.getAsJsonObject()
.entrySet()
.stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> e.getValue().isJsonPrimitive() ?
toPrimitive(e.getValue().getAsJsonPrimitive(), context)
: context.deserialize(e.getValue(), Employee.class)
));
}
private Object toPrimitive(JsonPrimitive jsonValue, JsonDeserializationContext context) {
if (jsonValue.isBoolean())
return jsonValue.getAsBoolean();
else if (jsonValue.isString())
return jsonValue.getAsString();
else {
BigDecimal bigDec = jsonValue.getAsBigDecimal();
Long l;
Integer i;
if ((i = toInteger(bigDec)) != null) {
return i;
} else if ((l = toLong(bigDec)) != null) {
return l;
} else {
return bigDec.doubleValue();
}
}
}
private Long toLong(BigDecimal val) {
try {
return val.toBigIntegerExact().longValue();
} catch (ArithmeticException e) {
return null;
}
}
private Integer toInteger(BigDecimal val) {
try {
return val.intValueExact();
} catch (ArithmeticException e) {
return null;
}
}
}
@@ -0,0 +1,44 @@
package com.baeldung.gson.serialization;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
public class StringDateMapDeserializer implements JsonDeserializer<Map<String, Date>> {
private static final Logger logger = LoggerFactory.getLogger(StringDateMapDeserializer.class);
private SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
@Override
public Map<String, Date> deserialize(JsonElement elem, Type type, JsonDeserializationContext jsonDeserializationContext) {
System.out.println("Deserializer called");
logger.info("Deserializer called");
return elem.getAsJsonObject()
.entrySet()
.stream()
.filter(e -> e.getValue().isJsonPrimitive())
.filter(e -> e.getValue().getAsJsonPrimitive().isString())
.collect(Collectors.toMap(Map.Entry::getKey, e -> formatDate(e.getValue())));
}
private Date formatDate(JsonElement value) {
try {
return format.parse(value.getAsString());
} catch (ParseException ex) {
throw new JsonParseException(ex);
}
}
}
@@ -0,0 +1,11 @@
package com.baeldung.gson.serializationwithexclusions;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Exclude {
}
@@ -0,0 +1,13 @@
package com.baeldung.gson.serializationwithexclusions;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class MyClass {
private long id;
private String name;
private String other;
private MySubClass subclass;
}
@@ -0,0 +1,20 @@
package com.baeldung.gson.serializationwithexclusions;
import com.google.gson.annotations.Expose;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class MyClassWithAnnotatedFields {
@Expose
private long id;
@Expose
private String name;
private String other;
@Expose
private MySubClassWithAnnotatedFields subclass;
}
@@ -0,0 +1,16 @@
package com.baeldung.gson.serializationwithexclusions;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class MyClassWithCustomAnnotatedFields {
private long id;
private String name;
@Exclude
private String other;
private MySubClassWithCustomAnnotatedFields subclass;
}
@@ -0,0 +1,15 @@
package com.baeldung.gson.serializationwithexclusions;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class MyClassWithTransientFields {
private long id;
private String name;
private transient String other;
private MySubClassWithTransientFields subclass;
}
@@ -0,0 +1,12 @@
package com.baeldung.gson.serializationwithexclusions;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class MySubClass {
private long id;
private String description;
private String otherVerboseInfo;
}
@@ -0,0 +1,15 @@
package com.baeldung.gson.serializationwithexclusions;
import com.google.gson.annotations.Expose;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class MySubClassWithAnnotatedFields {
@Expose private long id;
@Expose private String description;
private String otherVerboseInfo;
}
@@ -0,0 +1,14 @@
package com.baeldung.gson.serializationwithexclusions;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class MySubClassWithCustomAnnotatedFields {
private long id;
private String description;
@Exclude
private String otherVerboseInfo;
}
@@ -0,0 +1,13 @@
package com.baeldung.gson.serializationwithexclusions;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class MySubClassWithTransientFields {
private long id;
private String description;
private transient String otherVerboseInfo;
}