* Evaluation Article - Spring web-flux

* Evaluation Article - Spring web-flux

* Evaluation Article - Spring web-flux

* Evaluation Article - Spring web-flux

* core-scala: initial commit

* adding core-scala to pom

* Revert "core-scala: initial commit"

This reverts commit d46873405a.

* BAEL-2176

* inserting new lines between given, when and then parts

* Formatted using formatter

* indentation changed further

* Suggested changes in coding

* Adding Date Deserializer

* BAEL-2176: Switching to functional paradigm

* BAEL-2176

* BAEL-2176: changing HashMap to Map

* BAEL-2176: changed exception type

* BAEL-2176
This commit is contained in:
Swapan Pramanick 2018-10-31 18:47:17 +05:30 committed by KevinGilmore
parent b09fd15345
commit 586e911a02
3 changed files with 94 additions and 26 deletions

View File

@ -4,28 +4,26 @@ import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import org.baeldung.gson.entities.Employee;
import com.google.gson.*;
public class HashMapDeserializer implements JsonDeserializer<HashMap<String, Object>> {
public class MapDeserializer implements JsonDeserializer<Map<String, Object>> {
@Override
public HashMap<String, Object> deserialize(JsonElement elem, Type type, JsonDeserializationContext context) throws JsonParseException {
HashMap<String, Object> map = new HashMap<>();
for (Map.Entry<String, JsonElement> entry : elem.getAsJsonObject().entrySet()) {
JsonElement jsonValue = entry.getValue();
Object value = null;
if (jsonValue.isJsonPrimitive()) {
value = toPrimitive(jsonValue.getAsJsonPrimitive(), context);
} else {
value = context.deserialize(jsonValue, Employee.class);
}
map.put(entry.getKey(), value);
}
return map;
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) {

View File

@ -0,0 +1,44 @@
package org.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);
}
}
}

View File

@ -1,10 +1,14 @@
package org.baeldung.gson.deserialization;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.text.ParseException;
import java.util.Date;
import java.util.Map;
import org.apache.commons.lang3.time.DateUtils;
import org.baeldung.gson.entities.Employee;
import org.baeldung.gson.serialization.HashMapDeserializer;
import org.baeldung.gson.serialization.MapDeserializer;
import org.baeldung.gson.serialization.StringDateMapDeserializer;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
@ -16,18 +20,18 @@ import com.google.gson.JsonSyntaxException;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;
public class HashMapDeserializationUnitTest {
public class MapDeserializationUnitTest {
private static final Logger logger = LoggerFactory.getLogger(HashMapDeserializationUnitTest.class);
private static final Logger logger = LoggerFactory.getLogger(MapDeserializationUnitTest.class);
@Test
public void whenUsingHashMapClass_thenShouldReturnMapWithDefaultClasses() {
public void whenUsingMapClass_thenShouldReturnMapWithDefaultClasses() {
String jsonString = "{'employee.name':'Bob','employee.salary':10000, 'employee.active':true, "
+ "'employee':{'id':10, 'name': 'Bob Willis', 'address':'London'}}";
Gson gson = new Gson();
HashMap map = gson.fromJson(jsonString, HashMap.class);
Map map = gson.fromJson(jsonString, Map.class);
logger.info("The converted map: {}", map);
Assert.assertEquals(4, map.size());
@ -43,7 +47,7 @@ public class HashMapDeserializationUnitTest {
+ "'employee.active':true, " + "'employee':{'id':10, 'name': 'Bob Willis', 'address':'London'}}";
Gson gson = new Gson();
HashMap map = gson.fromJson(jsonString, HashMap.class);
Map map = gson.fromJson(jsonString, Map.class);
logger.info("The converted map: {}", map);
}
@ -56,8 +60,8 @@ public class HashMapDeserializationUnitTest {
+ "'Steve':{'id':10, 'name': 'Steven Waugh', 'address':'Australia'}}";
Gson gson = new Gson();
Type empMapType = new TypeToken<HashMap<String, Employee>>(){}.getType();
HashMap<String, Employee> nameEmployeeMap = gson.fromJson(jsonString, empMapType);
Type empMapType = new TypeToken<Map<String, Employee>>(){}.getType();
Map<String, Employee> nameEmployeeMap = gson.fromJson(jsonString, empMapType);
logger.info("The converted map: {}", nameEmployeeMap);
Assert.assertEquals(3, nameEmployeeMap.size());
@ -70,11 +74,11 @@ public class HashMapDeserializationUnitTest {
String jsonString = "{'employee.name':'Bob','employee.salary':10000, 'employee.active':true, "
+ "'employee':{'id':10, 'name': 'Bob Willis', 'address':'London'}}";
Type type = new TypeToken<HashMap<String, Object>>(){}.getType();
Type type = new TypeToken<Map<String, Object>>(){}.getType();
Gson gson = new GsonBuilder()
.registerTypeAdapter(type, new HashMapDeserializer())
.registerTypeAdapter(type, new MapDeserializer())
.create();
HashMap<String, Object> blendedMap = gson.fromJson(jsonString, type);
Map<String, Object> blendedMap = gson.fromJson(jsonString, type);
logger.info("The converted map: {}", blendedMap);
Assert.assertEquals(4, blendedMap.size());
@ -83,4 +87,26 @@ public class HashMapDeserializationUnitTest {
}
@Test
public void whenUsingCustomDateDeserializer_thenShouldReturnMapWithDate() {
String jsonString = "{'Bob': '2017/06/01', 'Jennie':'2015/01/03'}";
Type type = new TypeToken<Map<String, Date>>(){}.getType();
Gson gson = new GsonBuilder()
.registerTypeAdapter(type, new StringDateMapDeserializer())
.create();
Map<String, Date> empJoiningDateMap = gson.fromJson(jsonString, type);
logger.info("The converted map: {}", empJoiningDateMap);
logger.info("The map class {}", empJoiningDateMap.getClass());
Assert.assertEquals(2, empJoiningDateMap.size());
Assert.assertEquals(Date.class, empJoiningDateMap.get("Bob").getClass());
Date dt = null;
try {
dt = DateUtils.parseDate("2017-06-01", "yyyy-MM-dd");
Assert.assertEquals(dt, empJoiningDateMap.get("Bob"));
} catch (ParseException e) {
logger.error("Could not parse date", e);
}
}
}