Refs #BAEL-17 code for objectmapper.

This commit is contained in:
Ashanka Das 2016-07-14 01:37:45 +02:00
parent 41bf1d2f21
commit 53c32286be
14 changed files with 647 additions and 0 deletions

View File

@ -110,6 +110,31 @@
<scope>test</scope>
</dependency>
<!-- logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<!-- <scope>runtime</scope> -->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,40 @@
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.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
public class CustomCarDeserializer extends JsonDeserializer<Car>
{
protected final Logger Logger = LoggerFactory.getLogger(getClass());
public CustomCarDeserializer() { }
@Override
public Car deserialize(final JsonParser parser, final DeserializationContext deserializer) throws IOException, JsonProcessingException
{
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;
}
}

View File

@ -0,0 +1,22 @@
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.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
public class CustomCarSerializer extends JsonSerializer<Car>
{
public CustomCarSerializer() { }
@Override
public void serialize(final Car car, final JsonGenerator jsonGenerator, final SerializerProvider serializer) throws IOException, JsonProcessingException
{
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("car_brand", car.getType());
jsonGenerator.writeEndObject();
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.jackson.objectmapper;
public abstract class Example {
public abstract String name();
public abstract void execute();
}

View File

@ -0,0 +1,54 @@
package com.baeldung.jackson.objectmapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baeldung.jackson.objectmapper.dto.Car;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JavaToJsonExample extends Example
{
protected final Logger Logger = LoggerFactory.getLogger(getClass());
public JavaToJsonExample() { }
@Override
public String name()
{
return this.getClass().getName();
}
@Override
public void execute()
{
try
{
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);
}
catch(final Exception e)
{
Logger.error(e.toString());
}
}
class Request
{
Car car;
public Car getCar()
{
return car;
}
public void setCar(final Car car)
{
this.car = car;
}
}
}

View File

@ -0,0 +1,61 @@
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.Version;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
public class JsonAdvancedCustomSerializeExample extends Example
{
protected final Logger Logger = LoggerFactory.getLogger(getClass());
public JsonAdvancedCustomSerializeExample() { }
String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
@Override
public String name()
{
return this.getClass().getName();
}
@Override
public void execute()
{
Logger.debug("Executing: "+name());
try
{
ObjectMapper mapper = new ObjectMapper();
final SimpleModule module = new SimpleModule("CustomSerializer", new Version(1, 0, 0, null, null, null));
module.addSerializer(Car.class, new CustomCarSerializer());
mapper = new ObjectMapper();
mapper.registerModule(module);
final Car car = new Car("yellow", "renault");
final String carJson = mapper.writeValueAsString(car);
Logger.debug("car as json = " + carJson);
}
catch (final Exception e)
{
Logger.error(e.toString());
}
try
{
ObjectMapper mapper = new ObjectMapper();
final SimpleModule module = new SimpleModule("CustomCarDeserializer", new Version(1, 0, 0, null, null, null));
module.addDeserializer(Car.class, new CustomCarDeserializer());
mapper = new ObjectMapper();
mapper.registerModule(module);
final Car car = mapper.readValue(json, Car.class);
Logger.debug("car type = " + car.getType());
Logger.debug("car color = " + car.getColor());
}
catch (final Exception e)
{
Logger.error(e.toString());
}
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.jackson.objectmapper;
import java.io.StringWriter;
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.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class JsonAdvancedJsonNodeExample extends Example
{
protected final Logger Logger = LoggerFactory.getLogger(getClass());
public JsonAdvancedJsonNodeExample() { }
String jsonString = "{ \"color\" : \"Black\", \"type\" : \"Fiat\", \"year\" : \"1970\" }";
@Override
public String name()
{
return this.getClass().getName();
}
@Override
public void execute()
{
Logger.debug("Executing: "+name());
try
{
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 JsonNode jsonNodeYear = jsonNodeRoot.get("year");
final String year = jsonNodeYear.asText();
Logger.debug("Year = " + year);
Logger.debug("Color = " + car.getColor());
Logger.debug("Type = " + car.getType());
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
final StringWriter string = new StringWriter();
objectMapper.writeValue(string, car);
Logger.debug("Car JSON is:"+string);
}
catch (final Exception e)
{
Logger.error(e.toString());
}
}
}

View File

@ -0,0 +1,83 @@
package com.baeldung.jackson.objectmapper;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baeldung.jackson.objectmapper.dto.Car;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonArrayExample extends Example {
protected final Logger Logger = LoggerFactory.getLogger(getClass());
public JsonArrayExample() { }
@Override
public String name()
{
return this.getClass().getName();
}
@Override
public void execute()
{
Logger.debug("Executing: "+name());
try
{
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
final String jsonCarArray = "[{ \"color\" : \"Black\", \"type\" : \"BMW\" }, { \"color\" : \"Red\", \"type\" : \"FIAT\" }]";
final Car[] cars = objectMapper.readValue(jsonCarArray, Car[].class);
for(final Car car : cars)
{
Logger.debug("Color = " + car.getColor());
Logger.debug("Type = " + car.getType());
}
}
catch (final Exception e)
{
Logger.error(e.toString());
}
try
{
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true);
final String jsonCarArray = "[{ \"color\" : \"Black\", \"type\" : \"BMW\" }, { \"color\" : \"Red\", \"type\" : \"FIAT\" }]";
final List<Car> listCar = objectMapper.readValue(jsonCarArray, new TypeReference<List<Car>>(){});
for(final Car car : listCar)
{
Logger.debug("Color = " + car.getColor());
Logger.debug("Type = " + car.getType());
}
}
catch (final Exception e)
{
Logger.error(e.toString());
}
}
class Response {
public Response(final List<Car> cars) {
this.cars = cars;
}
List<Car> cars;
public List<Car> getCars() {
return cars;
}
public void setCars(final List<Car> cars) {
this.cars = cars;
}
}
}

View File

@ -0,0 +1,61 @@
package com.baeldung.jackson.objectmapper;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baeldung.jackson.objectmapper.dto.Car;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonDateExample extends Example {
protected final Logger Logger = LoggerFactory.getLogger(getClass());
public JsonDateExample() {
}
@Override
public String name() {
return this.getClass().getName();
}
@Override
public void execute() {
Logger.debug("Executing: " + name());
try {
final Car car = new Car("yellow", "renault");
final Request request = new Request();
request.setCar(car);
request.setDatePurchased(new Date());
final ObjectMapper objectMapper = new ObjectMapper();
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm a z");
objectMapper.setDateFormat(df);
final String carAsString = objectMapper.writeValueAsString(request);
Logger.debug(carAsString);
} catch (final Exception e) {
Logger.error(e.toString());
}
}
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;
}
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.jackson.objectmapper;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonMapExample extends Example {
protected final Logger Logger = LoggerFactory.getLogger(getClass());
public JsonMapExample() { }
@Override
public String name()
{
return this.getClass().getName();
}
@Override
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>>(){});
for(final String key : map.keySet())
{
Logger.debug("key = " + key + " | value = " + map.get(key));
}
}
catch (final Exception e)
{
Logger.error(e.toString());
}
}
}

View File

@ -0,0 +1,59 @@
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

@ -0,0 +1,69 @@
package com.baeldung.jackson.objectmapper;
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
{
protected final Logger Logger = LoggerFactory.getLogger(getClass());
public JsonToJavaExample() { }
String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
@Override
public String name()
{
return this.getClass().getName();
}
@Override
public void execute()
{
Logger.debug("Executing: "+name());
try
{
final ObjectMapper objectMapper = new ObjectMapper();
final Car car = objectMapper.readValue(json, Car.class);
Logger.debug("Color = " + car.getColor());
Logger.debug("Type = " + car.getType());
}
catch (final Exception e)
{
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;
}
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.jackson.objectmapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonToJsonNode extends Example
{
protected final Logger Logger = LoggerFactory.getLogger(getClass());
public JsonToJsonNode() { }
String jsonString = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
@Override
public String name()
{
return this.getClass().getName();
}
@Override
public void execute()
{
Logger.debug("Executing: "+name());
try
{
final ObjectMapper objectMapper = new ObjectMapper();
final JsonNode jsonNode = objectMapper.readTree(jsonString);
Logger.debug(jsonNode.get("color").asText());
}
catch (final Exception e)
{
Logger.error(e.toString());
}
}
}

View File

@ -0,0 +1,30 @@
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;
}
}