Merge remote-tracking branch 'origin/pr/498' into pr/498-ask-das-objectmapper

Conflicts:
	jackson/src/test/java/com/baeldung/jackson/objectmapper/JavaToJsonExample.java
	jackson/src/test/java/com/baeldung/jackson/objectmapper/JsonAdvancedCustomSerializeExample.java
	jackson/src/test/java/com/baeldung/jackson/objectmapper/JsonAdvancedJsonNodeExample.java
	jackson/src/test/java/com/baeldung/jackson/objectmapper/JsonArrayExample.java
	jackson/src/test/java/com/baeldung/jackson/objectmapper/JsonDateExample.java
	jackson/src/test/java/com/baeldung/jackson/objectmapper/JsonMapExample.java
	jackson/src/test/java/com/baeldung/jackson/objectmapper/JsonParserExample.java
	jackson/src/test/java/com/baeldung/jackson/objectmapper/JsonToJavaExample.java
	jackson/src/test/java/com/baeldung/jackson/objectmapper/JsonToJsonNode.java
This commit is contained in:
Slavisa Baeldung 2016-07-18 12:25:34 +02:00
commit ffbd7f0d0d
12 changed files with 158 additions and 273 deletions

View File

@ -29,7 +29,7 @@
</classpathentry> </classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes> <attributes>
<attribute name="owner.project.facets" value="java"/> <attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry kind="output" path="target/classes"/> <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 public void serialize(final Car car, final JsonGenerator jsonGenerator, final SerializerProvider serializer) throws IOException, JsonProcessingException
{ {
jsonGenerator.writeStartObject(); jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("car_brand", car.getType()); jsonGenerator.writeStringField("model: ", car.getType());
jsonGenerator.writeEndObject(); jsonGenerator.writeEndObject();
} }
} }

View File

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

View File

@ -1,9 +1,13 @@
package com.baeldung.jackson.objectmapper; package com.baeldung.jackson.objectmapper;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baeldung.jackson.objectmapper.dto.Car; import com.baeldung.jackson.objectmapper.dto.Car;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JavaToJsonExample extends Example public class JavaToJsonExample extends Example
{ {
@ -19,35 +23,11 @@ public class JavaToJsonExample extends Example
} }
@Override @Override
public void execute() public void testExample() throws Exception {
{
try
{
final ObjectMapper objectMapper = new ObjectMapper(); final ObjectMapper objectMapper = new ObjectMapper();
final Car car = new Car("yellow", "renault"); final Car car = new Car("yellow", "renault");
final Request request = new Request();
request.setCar(car);
final String carAsString = objectMapper.writeValueAsString(car); final String carAsString = objectMapper.writeValueAsString(car);
Logger.debug(carAsString); assertThat(carAsString, containsString("yellow"));
} assertThat(carAsString, containsString("renault"));
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

@ -1,5 +1,10 @@
package com.baeldung.jackson.objectmapper; 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.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -8,46 +13,35 @@ import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.module.SimpleModule;
public class JsonAdvancedCustomSerializeExample extends Example { public class JsonAdvancedCustomSerializeExample extends Example
{
protected final Logger Logger = LoggerFactory.getLogger(getClass()); protected final Logger Logger = LoggerFactory.getLogger(getClass());
public JsonAdvancedCustomSerializeExample() { public JsonAdvancedCustomSerializeExample() { }
}
String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
@Override @Override
public String name() { public String name()
{
return this.getClass().getName(); return this.getClass().getName();
} }
@Override @Override
public void execute() { public void testExample() throws Exception {
Logger.debug("Executing: " + name()); final ObjectMapper mapper = new ObjectMapper();
try { final SimpleModule serializerModule = new SimpleModule("CustomSerializer", new Version(1, 0, 0, null, null, null));
ObjectMapper mapper = new ObjectMapper(); serializerModule.addSerializer(Car.class, new CustomCarSerializer());
final SimpleModule module = new SimpleModule("CustomSerializer", new Version(1, 0, 0, null, null, null)); mapper.registerModule(serializerModule);
module.addSerializer(Car.class, new CustomCarSerializer());
mapper = new ObjectMapper();
mapper.registerModule(module);
final Car car = new Car("yellow", "renault"); final Car car = new Car("yellow", "renault");
final String carJson = mapper.writeValueAsString(car); final String carJson = mapper.writeValueAsString(car);
Logger.debug("car as json = " + carJson); assertThat(carJson, containsString("renault"));
} catch (final Exception e) { assertThat(carJson, containsString("model"));
Logger.error(e.toString());
} final SimpleModule deserializerModule = new SimpleModule("CustomCarDeserializer", new Version(1, 0, 0, null, null, null));
try { deserializerModule.addDeserializer(Car.class, new CustomCarDeserializer());
ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(deserializerModule);
final SimpleModule module = new SimpleModule("CustomCarDeserializer", new Version(1, 0, 0, null, null, null)); final Car carResult = mapper.readValue(EXAMPLE_JSON, Car.class);
module.addDeserializer(Car.class, new CustomCarDeserializer()); assertNotNull(carResult);
mapper = new ObjectMapper(); assertThat(carResult.getColor(), equalTo("Black"));
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

@ -1,6 +1,9 @@
package com.baeldung.jackson.objectmapper; package com.baeldung.jackson.objectmapper;
import java.io.StringWriter; 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.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -9,43 +12,34 @@ import com.baeldung.jackson.objectmapper.dto.Car;
import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class JsonAdvancedJsonNodeExample extends Example { public class JsonAdvancedJsonNodeExample extends Example
{
protected final Logger Logger = LoggerFactory.getLogger(getClass()); protected final Logger Logger = LoggerFactory.getLogger(getClass());
public JsonAdvancedJsonNodeExample() { public JsonAdvancedJsonNodeExample() { }
}
String jsonString = "{ \"color\" : \"Black\", \"type\" : \"Fiat\", \"year\" : \"1970\" }"; String LOCAL_JSON = "{ \"color\" : \"Black\", \"type\" : \"Fiat\", \"year\" : \"1970\" }";
@Override @Override
public String name() { public String name()
{
return this.getClass().getName(); return this.getClass().getName();
} }
@Override @Override
public void execute() { public void testExample() throws Exception {
Logger.debug("Executing: " + name());
try {
final ObjectMapper objectMapper = new ObjectMapper(); final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
final Car car = objectMapper.readValue(jsonString, Car.class); final Car car = objectMapper.readValue(LOCAL_JSON, Car.class);
final JsonNode jsonNodeRoot = objectMapper.readTree(jsonString); final JsonNode jsonNodeRoot = objectMapper.readTree(LOCAL_JSON);
final JsonNode jsonNodeYear = jsonNodeRoot.get("year"); final JsonNode jsonNodeYear = jsonNodeRoot.get("year");
final String year = jsonNodeYear.asText(); 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); assertNotNull(car);
final StringWriter string = new StringWriter(); assertThat(car.getColor(), equalTo("Black"));
objectMapper.writeValue(string, car); assertThat(year, containsString("1970"));
Logger.debug("Car JSON is:" + string);
} catch (final Exception e) {
Logger.error(e.toString());
} }
} }
}

View File

@ -1,7 +1,12 @@
package com.baeldung.jackson.objectmapper; 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 java.util.List;
import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -14,46 +19,14 @@ public class JsonArrayExample extends Example {
protected final Logger Logger = LoggerFactory.getLogger(getClass()); protected final Logger Logger = LoggerFactory.getLogger(getClass());
public JsonArrayExample() { public JsonArrayExample() { }
}
@Override @Override
public String name() { public String name()
{
return this.getClass().getName(); 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 { class Response {
public Response(final List<Car> cars) { public Response(final List<Car> cars) {
@ -72,4 +45,24 @@ public class JsonArrayExample extends Example {
} }
final String LOCAL_JSON = "[{ \"color\" : \"Black\", \"type\" : \"BMW\" }, { \"color\" : \"Red\", \"type\" : \"BMW\" }]";
@Override
@Test
public void testExample() 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; 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.DateFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
@ -22,28 +26,9 @@ public class JsonDateExample extends Example {
return this.getClass().getName(); 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 { class Request {
Car car; Car car;
Date datePurchased; Date datePurchased;
public Car getCar() { public Car getCar() {
return car; return car;
} }
@ -60,4 +45,18 @@ public class JsonDateExample extends Example {
this.datePurchased = datePurchased; this.datePurchased = datePurchased;
} }
} }
@Override
public void testExample() 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; package com.baeldung.jackson.objectmapper;
import static org.junit.Assert.assertNotNull;
import java.util.Map; import java.util.Map;
import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -12,26 +15,23 @@ public class JsonMapExample extends Example {
protected final Logger Logger = LoggerFactory.getLogger(getClass()); protected final Logger Logger = LoggerFactory.getLogger(getClass());
public JsonMapExample() { public JsonMapExample() { }
}
@Override @Override
public String name() { public String name()
{
return this.getClass().getName(); return this.getClass().getName();
} }
@Override @Override
public void execute() { @Test
public void testExample() throws Exception {
final ObjectMapper objectMapper = new ObjectMapper(); final ObjectMapper objectMapper = new ObjectMapper();
final String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }"; final Map<String, Object> map = objectMapper.readValue(EXAMPLE_JSON, new TypeReference<Map<String, Object>>() {
try {
final Map<String, Object> map = objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {
}); });
assertNotNull(map);
for (final String key : map.keySet()) { for (final String key : map.keySet()) {
Logger.debug("key = " + key + " | value = " + map.get(key)); assertNotNull(key);
}
} catch (final Exception e) {
Logger.error(e.toString());
} }
} }
} }

View File

@ -1,54 +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,61 +1,34 @@
package com.baeldung.jackson.objectmapper; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.baeldung.jackson.objectmapper.dto.Car; import com.baeldung.jackson.objectmapper.dto.Car;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonToJavaExample extends Example { public class JsonToJavaExample extends Example
{
protected final Logger Logger = LoggerFactory.getLogger(getClass()); protected final Logger Logger = LoggerFactory.getLogger(getClass());
public JsonToJavaExample() { public JsonToJavaExample() { }
}
String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
@Override @Override
public String name() { public String name()
{
return this.getClass().getName(); return this.getClass().getName();
} }
@Override @Override
public void execute() { @Test
Logger.debug("Executing: " + name()); public void testExample() throws Exception {
try {
final ObjectMapper objectMapper = new ObjectMapper(); 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()); assertNotNull(car);
Logger.debug("Type = " + car.getType()); assertThat(car.getColor(), containsString("Black"));
} 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

@ -1,33 +1,34 @@
package com.baeldung.jackson.objectmapper; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonToJsonNode extends Example { public class JsonToJsonNode extends Example
{
protected final Logger Logger = LoggerFactory.getLogger(getClass()); protected final Logger Logger = LoggerFactory.getLogger(getClass());
public JsonToJsonNode() { public JsonToJsonNode() { }
}
String jsonString = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
@Override @Override
public String name() { public String name()
{
return this.getClass().getName(); return this.getClass().getName();
} }
@Override @Override
public void execute() { @Test
Logger.debug("Executing: " + name()); public void testExample() throws Exception {
try {
final ObjectMapper objectMapper = new ObjectMapper(); final ObjectMapper objectMapper = new ObjectMapper();
final JsonNode jsonNode = objectMapper.readTree(jsonString); final JsonNode jsonNode = objectMapper.readTree(EXAMPLE_JSON);
Logger.debug(jsonNode.get("color").asText()); assertNotNull(jsonNode);
} catch (final Exception e) { assertThat(jsonNode.get("color").asText(), containsString("Black"));
Logger.error(e.toString());
}
} }
} }