Refs #BAEL-17 code for objectmapper. Added JUnit Test cases.

This commit is contained in:
Ashanka Das 2016-07-17 01:19:44 +02:00
parent 53c32286be
commit f14f2af421
12 changed files with 160 additions and 118 deletions

View File

@ -29,7 +29,7 @@
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes>
<attribute name="owner.project.facets" value="java"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>

View File

@ -16,7 +16,7 @@ public class CustomCarSerializer extends JsonSerializer<Car>
public void serialize(final Car car, final JsonGenerator jsonGenerator, final SerializerProvider serializer) throws IOException, JsonProcessingException
{
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("car_brand", car.getType());
jsonGenerator.writeStringField("model: ", car.getType());
jsonGenerator.writeEndObject();
}
}

View File

@ -1,8 +1,15 @@
package com.baeldung.jackson.objectmapper;
import org.junit.Test;
public abstract class Example {
String EXAMPLE_JSON = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
public abstract String name();
public abstract void execute();
@Test
public abstract void test() throws Exception;
}

View File

@ -1,5 +1,9 @@
package com.baeldung.jackson.objectmapper;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -26,8 +30,6 @@ public class JavaToJsonExample extends Example
{
final ObjectMapper objectMapper = new ObjectMapper();
final Car car = new Car("yellow", "renault");
final Request request = new Request();
request.setCar(car);
final String carAsString = objectMapper.writeValueAsString(car);
Logger.debug(carAsString);
}
@ -37,18 +39,13 @@ public class JavaToJsonExample extends Example
}
}
class Request
{
Car car;
public Car getCar()
{
return car;
}
public void setCar(final Car car)
{
this.car = car;
}
@Override
@Test
public void test() 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"));
}
}

View File

@ -1,5 +1,11 @@
package com.baeldung.jackson.objectmapper;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -15,8 +21,6 @@ public class JsonAdvancedCustomSerializeExample extends Example
public JsonAdvancedCustomSerializeExample() { }
String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
@Override
public String name()
{
@ -49,7 +53,7 @@ public class JsonAdvancedCustomSerializeExample extends Example
module.addDeserializer(Car.class, new CustomCarDeserializer());
mapper = new ObjectMapper();
mapper.registerModule(module);
final Car car = mapper.readValue(json, Car.class);
final Car car = mapper.readValue(EXAMPLE_JSON, Car.class);
Logger.debug("car type = " + car.getType());
Logger.debug("car color = " + car.getColor());
}
@ -58,4 +62,24 @@ public class JsonAdvancedCustomSerializeExample extends Example
Logger.error(e.toString());
}
}
@Override
@Test
public void test() 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"));
}
}

View File

@ -1,7 +1,13 @@
package com.baeldung.jackson.objectmapper;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import java.io.StringWriter;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -18,7 +24,7 @@ public class JsonAdvancedJsonNodeExample extends Example
public JsonAdvancedJsonNodeExample() { }
String jsonString = "{ \"color\" : \"Black\", \"type\" : \"Fiat\", \"year\" : \"1970\" }";
String LOCAL_JSON = "{ \"color\" : \"Black\", \"type\" : \"Fiat\", \"year\" : \"1970\" }";
@Override
public String name()
@ -34,8 +40,8 @@ public class JsonAdvancedJsonNodeExample extends Example
{
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
final Car car = objectMapper.readValue(jsonString, Car.class);
final JsonNode jsonNodeRoot = objectMapper.readTree(jsonString);
final Car car = objectMapper.readValue(LOCAL_JSON, Car.class);
final JsonNode jsonNodeRoot = objectMapper.readTree(LOCAL_JSON);
final JsonNode jsonNodeYear = jsonNodeRoot.get("year");
final String year = jsonNodeYear.asText();
Logger.debug("Year = " + year);
@ -53,4 +59,19 @@ public class JsonAdvancedJsonNodeExample extends Example
}
}
@Override
@Test
public void test() throws Exception {
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
final Car car = objectMapper.readValue(LOCAL_JSON, Car.class);
final JsonNode jsonNodeRoot = objectMapper.readTree(LOCAL_JSON);
final JsonNode jsonNodeYear = jsonNodeRoot.get("year");
final String year = jsonNodeYear.asText();
assertNotNull(car);
assertThat(car.getColor(), equalTo("Black"));
assertThat(year, containsString("1970"));
}
}

View File

@ -1,7 +1,12 @@
package com.baeldung.jackson.objectmapper;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -80,4 +85,24 @@ public class JsonArrayExample extends Example {
}
final String LOCAL_JSON = "[{ \"color\" : \"Black\", \"type\" : \"BMW\" }, { \"color\" : \"Red\", \"type\" : \"BMW\" }]";
@Override
@Test
public void test() throws Exception {
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
final Car[] cars = objectMapper.readValue(LOCAL_JSON, Car[].class);
for (final Car car : cars) {
assertNotNull(car);
assertThat(car.getType(), equalTo("BMW"));
}
final List<Car> listCar = objectMapper.readValue(LOCAL_JSON, new TypeReference<List<Car>>() {
});
for (final Car car : listCar) {
assertNotNull(car);
assertThat(car.getType(), equalTo("BMW"));
}
}
}

View File

@ -1,5 +1,9 @@
package com.baeldung.jackson.objectmapper;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
@ -58,4 +62,18 @@ public class JsonDateExample extends Example {
this.datePurchased = datePurchased;
}
}
@Override
public void test() 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"));
}
}

View File

@ -1,7 +1,10 @@
package com.baeldung.jackson.objectmapper;
import static org.junit.Assert.assertNotNull;
import java.util.Map;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -24,10 +27,10 @@ public class JsonMapExample extends Example {
public void execute()
{
final ObjectMapper objectMapper = new ObjectMapper();
final String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
try
{
final Map<String, Object> map = objectMapper.readValue(json, new TypeReference<Map<String,Object>>(){});
final Map<String, Object> map = objectMapper.readValue(EXAMPLE_JSON, new TypeReference<Map<String, Object>>() {
});
for(final String key : map.keySet())
{
Logger.debug("key = " + key + " | value = " + map.get(key));
@ -38,4 +41,16 @@ public class JsonMapExample extends Example {
Logger.error(e.toString());
}
}
@Override
@Test
public void test() 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);
}
}
}

View File

@ -1,59 +0,0 @@
package com.baeldung.jackson.objectmapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baeldung.jackson.objectmapper.dto.Car;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
public class JsonParserExample extends Example {
protected final Logger Logger = LoggerFactory.getLogger(getClass());
public JsonParserExample() { }
@Override
public String name()
{
return this.getClass().getName();
}
@Override
public void execute()
{
Logger.debug("Executing: "+name());
final String carJson = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
final JsonFactory factory = new JsonFactory();
JsonParser parser;
try
{
final Car car = new Car();
parser = factory.createParser(carJson);
while(!parser.isClosed())
{
JsonToken jsonToken = parser.nextToken();
Logger.debug("jsonToken = " + jsonToken);
if(JsonToken.FIELD_NAME.equals(jsonToken)){
final String fieldName = parser.getCurrentName();
System.out.println(fieldName);
jsonToken = parser.nextToken();
if("color".equals(fieldName)){
car.setColor(parser.getValueAsString());
} else if ("type".equals(fieldName)){
car.setType(parser.getValueAsString());
}
}
}
Logger.debug("car:"+car.getColor());
}
catch (final Exception e)
{
Logger.error(e.toString());
}
}
}

View File

@ -1,10 +1,14 @@
package com.baeldung.jackson.objectmapper;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baeldung.jackson.objectmapper.dto.Car;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonToJavaExample extends Example
@ -13,8 +17,6 @@ public class JsonToJavaExample extends Example
public JsonToJavaExample() { }
String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
@Override
public String name()
{
@ -28,7 +30,7 @@ public class JsonToJavaExample extends Example
try
{
final ObjectMapper objectMapper = new ObjectMapper();
final Car car = objectMapper.readValue(json, Car.class);
final Car car = objectMapper.readValue(EXAMPLE_JSON, Car.class);
Logger.debug("Color = " + car.getColor());
Logger.debug("Type = " + car.getType());
}
@ -36,34 +38,14 @@ public class JsonToJavaExample extends Example
{
Logger.error(e.toString());
}
try
{
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
final String jsonCar = "\"car\" : { \"color\" : \"Red\", \"type\" : \"FIAT\" }";
final Response response = objectMapper.readValue(jsonCar, Response.class);
Logger.debug("response: "+response);
}
catch (final Exception e)
{
Logger.error(e.toString());
}
}
class Response {
Car car;
public Car getCar() {
return car;
}
public void setCars(final Car car) {
this.car = car;
}
@Override
@Test
public void test() throws Exception {
final ObjectMapper objectMapper = new ObjectMapper();
final Car car = objectMapper.readValue(EXAMPLE_JSON, Car.class);
assertNotNull(car);
assertThat(car.getColor(), containsString("Black"));
}
}

View File

@ -1,5 +1,10 @@
package com.baeldung.jackson.objectmapper;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -12,8 +17,6 @@ public class JsonToJsonNode extends Example
public JsonToJsonNode() { }
String jsonString = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
@Override
public String name()
{
@ -27,7 +30,7 @@ public class JsonToJsonNode extends Example
try
{
final ObjectMapper objectMapper = new ObjectMapper();
final JsonNode jsonNode = objectMapper.readTree(jsonString);
final JsonNode jsonNode = objectMapper.readTree(EXAMPLE_JSON);
Logger.debug(jsonNode.get("color").asText());
}
catch (final Exception e)
@ -35,4 +38,13 @@ public class JsonToJsonNode extends Example
Logger.error(e.toString());
}
}
@Override
@Test
public void test() throws Exception {
final ObjectMapper objectMapper = new ObjectMapper();
final JsonNode jsonNode = objectMapper.readTree(EXAMPLE_JSON);
assertNotNull(jsonNode);
assertThat(jsonNode.get("color").asText(), containsString("Black"));
}
}