[BAEL-19675] - Move articles out of jackson part 2

This commit is contained in:
catalin-burcea 2019-11-26 12:28:18 +02:00
parent 9f25b72ca4
commit 3d35439fb5
119 changed files with 1087 additions and 469 deletions

View File

@ -6,10 +6,7 @@ This module contains articles about Jackson.
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [Mapping Multiple JSON Fields to a Single Java Field](https://www.baeldung.com/json-multiple-fields-single-java-field)
- [How to Process YAML with Jackson](https://www.baeldung.com/jackson-yaml)
- [Working with Tree Model Nodes in Jackson](https://www.baeldung.com/jackson-json-node-tree-model)
- [Converting JSON to CSV in Java](https://www.baeldung.com/java-converting-json-to-csv)
- [Compare Two JSON Objects with Jackson](https://www.baeldung.com/jackson-compare-two-json-objects)
- [Calling Default Serializer from Custom Serializer in Jackson](https://www.baeldung.com/jackson-call-default-serializer-from-custom-serializer)
- More articles: [[<-- prev]](/../jackson)

View File

@ -14,20 +14,6 @@
<dependencies>
<!-- YAML -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- CSV -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-csv</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- Allow use of LocalDate -->
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>

View File

@ -18,7 +18,6 @@ import com.baeldung.jackson.ignore.dtos.MyMixInForIgnoreType;
import com.baeldung.jackson.ignore.dtos.MyDtoIgnoreField;
import com.baeldung.jackson.ignore.dtos.MyDtoIgnoreFieldByName;
import com.baeldung.jackson.ignore.dtos.MyDtoIgnoreNull;
import com.baeldung.jackson.ignore.dtos.MyDtoNullKeySerializer;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
@ -191,88 +190,4 @@ public class JacksonSerializationIgnoreUnitTest {
System.out.println(dtoAsString);
}
// map
@Test
public final void givenIgnoringMapNullValue_whenWritingMapObjectWithNullValue_thenIgnored() throws JsonProcessingException {
final ObjectMapper mapper = new ObjectMapper();
// mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
mapper.setSerializationInclusion(Include.NON_NULL);
final MyDto dtoObject1 = new MyDto();
final Map<String, MyDto> dtoMap = new HashMap<String, MyDto>();
dtoMap.put("dtoObject1", dtoObject1);
dtoMap.put("dtoObject2", null);
final String dtoMapAsString = mapper.writeValueAsString(dtoMap);
assertThat(dtoMapAsString, containsString("dtoObject1"));
assertThat(dtoMapAsString, not(containsString("dtoObject2")));
System.out.println(dtoMapAsString);
}
@Test
public final void givenIgnoringMapValueObjectWithNullField_whenWritingMapValueObjectWithNullField_thenIgnored() throws JsonProcessingException {
final ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
final MyDto dtoObject = new MyDto();
final Map<String, MyDto> dtoMap = new HashMap<String, MyDto>();
dtoMap.put("dtoObject", dtoObject);
final String dtoMapAsString = mapper.writeValueAsString(dtoMap);
assertThat(dtoMapAsString, containsString("dtoObject"));
assertThat(dtoMapAsString, not(containsString("stringValue")));
System.out.println(dtoMapAsString);
}
@Test
public final void givenAllowingMapObjectWithNullKey_whenWriting_thenCorrect() throws JsonProcessingException {
final ObjectMapper mapper = new ObjectMapper();
mapper.getSerializerProvider()
.setNullKeySerializer(new MyDtoNullKeySerializer());
final MyDto dtoObject1 = new MyDto();
dtoObject1.setStringValue("dtoObjectString1");
final MyDto dtoObject2 = new MyDto();
dtoObject2.setStringValue("dtoObjectString2");
final Map<String, MyDto> dtoMap = new HashMap<String, MyDto>();
dtoMap.put(null, dtoObject1);
dtoMap.put("obj2", dtoObject2);
final String dtoMapAsString = mapper.writeValueAsString(dtoMap);
System.out.println(dtoMapAsString);
assertThat(dtoMapAsString, containsString("\"\""));
assertThat(dtoMapAsString, containsString("dtoObjectString1"));
assertThat(dtoMapAsString, containsString("obj2"));
}
@Test
public final void givenAllowingMapObjectOneNullKey_whenWritingMapObjectWithTwoNullKeys_thenOverride() throws JsonProcessingException {
final ObjectMapper mapper = new ObjectMapper();
mapper.getSerializerProvider()
.setNullKeySerializer(new MyDtoNullKeySerializer());
final MyDto dtoObject1 = new MyDto();
dtoObject1.setStringValue("dtoObject1String");
final MyDto dtoObject2 = new MyDto();
dtoObject2.setStringValue("dtoObject2String");
final Map<String, MyDto> dtoMap = new HashMap<String, MyDto>();
dtoMap.put(null, dtoObject1);
dtoMap.put(null, dtoObject2);
final String dtoMapAsString = mapper.writeValueAsString(dtoMap);
assertThat(dtoMapAsString, not(containsString("dtoObject1String")));
assertThat(dtoMapAsString, containsString("dtoObject2String"));
System.out.println(dtoMapAsString);
}
}

View File

@ -0,0 +1,14 @@
## Jackson Conversions
This module contains articles about Jackson conversions.
### Relevant Articles:
- [Mapping a Dynamic JSON Object with Jackson](https://www.baeldung.com/jackson-mapping-dynamic-object)
- [Jackson Unmarshalling JSON with Unknown Properties](https://www.baeldung.com/jackson-deserialize-json-unknown-properties)
- [Ignore Null Fields with Jackson](https://www.baeldung.com/jackson-ignore-null-fields)
- [Mapping Multiple JSON Fields to a Single Java Field](https://www.baeldung.com/json-multiple-fields-single-java-field)
- [Convert XML to JSON Using Jackson](https://www.baeldung.com/jackson-convert-xml-json)
- [Converting JSON to CSV in Java](https://www.baeldung.com/java-converting-json-to-csv)
- [How to Process YAML with Jackson](https://www.baeldung.com/jackson-yaml)
- [Jackson Streaming API](https://www.baeldung.com/jackson-streaming-api)
- More articles: [[<-- prev]](../jackson-conversions)

View File

@ -0,0 +1,67 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>jackson-conversions-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jackson-conversions-2</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!--jackson for xml -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- YAML -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- Allow use of LocalDate -->
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.9.8</version>
</dependency>
<!-- CSV -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-csv</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>jackson-conversions-2</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<assertj.version>3.11.0</assertj.version>
</properties>
</project>

View File

@ -3,8 +3,6 @@ package com.baeldung.jackson.csv;
import java.io.File;
import java.io.IOException;
import com.baeldung.jackson.entities.OrderLine;
import com.baeldung.jackson.mixin.OrderLineForCsv;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.databind.ObjectMapper;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.entities;
package com.baeldung.jackson.csv;
import java.math.BigDecimal;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.mixin;
package com.baeldung.jackson.csv;
import java.math.BigDecimal;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deserialization.dynamicobject;
package com.baeldung.jackson.dynamicobject;
import java.util.LinkedHashMap;
import java.util.Map;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deserialization.dynamicobject;
package com.baeldung.jackson.dynamicobject;
import com.fasterxml.jackson.databind.JsonNode;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deserialization.dynamicobject;
package com.baeldung.jackson.dynamicobject;
import java.util.Map;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.entities;
package com.baeldung.jackson.multiplefields;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonProperty;

View File

@ -0,0 +1,54 @@
package com.baeldung.jackson.unknownproperties;
public class MyDto {
private String stringValue;
private int intValue;
private boolean booleanValue;
public MyDto() {
super();
}
public MyDto(final String stringValue, final int intValue, final boolean booleanValue) {
super();
this.stringValue = stringValue;
this.intValue = intValue;
this.booleanValue = booleanValue;
}
// API
public String getStringValue() {
return stringValue;
}
public void setStringValue(final String stringValue) {
this.stringValue = stringValue;
}
public int getIntValue() {
return intValue;
}
public void setIntValue(final int intValue) {
this.intValue = intValue;
}
public boolean isBooleanValue() {
return booleanValue;
}
public void setBooleanValue(final boolean booleanValue) {
this.booleanValue = booleanValue;
}
//
@Override
public String toString() {
return "MyDto [stringValue=" + stringValue + ", intValue=" + intValue + ", booleanValue=" + booleanValue + "]";
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.dtos.ignore;
package com.baeldung.jackson.unknownproperties;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.dtos.ignore;
package com.baeldung.jackson.unknownproperties;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.entities;
package com.baeldung.jackson.yaml;
import java.time.LocalDate;
import java.util.ArrayList;

View File

@ -0,0 +1,49 @@
package com.baeldung.jackson.yaml;
import java.math.BigDecimal;
public class OrderLine {
private String item;
private int quantity;
private BigDecimal unitPrice;
public OrderLine() {
}
public OrderLine(String item, int quantity, BigDecimal unitPrice) {
super();
this.item = item;
this.quantity = quantity;
this.unitPrice = unitPrice;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public BigDecimal getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(BigDecimal unitPrice) {
this.unitPrice = unitPrice;
}
@Override
public String toString() {
return "OrderLine [item=" + item + ", quantity=" + quantity + ", unitPrice=" + unitPrice + "]";
}
}

View File

@ -18,30 +18,30 @@ public class CsvUnitTest {
@Test
public void givenJsonInput_thenWriteCsv() throws JsonParseException, JsonMappingException, IOException {
JsonCsvConverter.JsonToCsv(new File("src/main/resources/orderLines.json"),
new File("src/main/resources/csvFromJson.csv"));
JsonCsvConverter.JsonToCsv(new File("src/main/resources/csv/orderLines.json"),
new File("src/main/resources/csv/csvFromJson.csv"));
assertEquals(readFile("src/main/resources/csvFromJson.csv"),
readFile("src/test/resources/expectedCsvFromJson.csv"));
assertEquals(readFile("src/main/resources/csv/csvFromJson.csv"),
readFile("src/test/resources/csv/expectedCsvFromJson.csv"));
}
@Test
public void givenCsvInput_thenWritesJson() throws JsonParseException, JsonMappingException, IOException {
JsonCsvConverter.csvToJson(new File("src/main/resources/orderLines.csv"),
new File("src/main/resources/jsonFromCsv.json"));
JsonCsvConverter.csvToJson(new File("src/main/resources/csv/orderLines.csv"),
new File("src/main/resources/csv/jsonFromCsv.json"));
assertEquals(readFile("src/main/resources/jsonFromCsv.json"),
readFile("src/test/resources/expectedJsonFromCsv.json"));
assertEquals(readFile("src/main/resources/csv/jsonFromCsv.json"),
readFile("src/test/resources/csv/expectedJsonFromCsv.json"));
}
@Test
public void givenJsonInput_thenWriteFormattedCsvOutput() throws JsonParseException, JsonMappingException, IOException {
JsonCsvConverter.JsonToFormattedCsv(new File("src/main/resources/orderLines.json"),
new File("src/main/resources/formattedCsvFromJson.csv"));
JsonCsvConverter.JsonToFormattedCsv(new File("src/main/resources/csv/orderLines.json"),
new File("src/main/resources/csv/formattedCsvFromJson.csv"));
assertEquals(readFile("src/main/resources/formattedCsvFromJson.csv"),
readFile("src/test/resources/expectedFormattedCsvFromJson.csv"));
assertEquals(readFile("src/main/resources/csv/formattedCsvFromJson.csv"),
readFile("src/test/resources/csv/expectedFormattedCsvFromJson.csv"));
}

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deserialization.dynamicobject;
package com.baeldung.jackson.dynamicobject;
import static org.assertj.core.api.Assertions.assertThat;

View File

@ -0,0 +1,52 @@
package com.baeldung.jackson.ignorenullfields;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.PropertyFilter;
import com.fasterxml.jackson.databind.ser.PropertyWriter;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
public class IgnoreNullFieldsUnitTest {
@Test
public final void givenNullsIgnoredOnClass_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException {
final ObjectMapper mapper = new ObjectMapper();
final MyDtoIgnoreNull dtoObject = new MyDtoIgnoreNull();
final String dtoAsString = mapper.writeValueAsString(dtoObject);
assertThat(dtoAsString, containsString("intValue"));
assertThat(dtoAsString, containsString("booleanValue"));
assertThat(dtoAsString, not(containsString("stringValue")));
System.out.println(dtoAsString);
}
@Test
public final void givenNullsIgnoredGlobally_whenWritingObjectWithNullField_thenIgnored() throws JsonProcessingException {
final ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
final MyDto dtoObject = new MyDto();
final String dtoAsString = mapper.writeValueAsString(dtoObject);
assertThat(dtoAsString, containsString("intValue"));
assertThat(dtoAsString, containsString("booleanValue"));
assertThat(dtoAsString, not(containsString("stringValue")));
System.out.println(dtoAsString);
}
}

View File

@ -0,0 +1,54 @@
package com.baeldung.jackson.ignorenullfields;
public class MyDto {
private String stringValue;
private int intValue;
private boolean booleanValue;
public MyDto() {
super();
}
public MyDto(final String stringValue, final int intValue, final boolean booleanValue) {
super();
this.stringValue = stringValue;
this.intValue = intValue;
this.booleanValue = booleanValue;
}
// API
public String getStringValue() {
return stringValue;
}
public void setStringValue(final String stringValue) {
this.stringValue = stringValue;
}
public int getIntValue() {
return intValue;
}
public void setIntValue(final int intValue) {
this.intValue = intValue;
}
public boolean isBooleanValue() {
return booleanValue;
}
public void setBooleanValue(final boolean booleanValue) {
this.booleanValue = booleanValue;
}
//
@Override
public String toString() {
return "MyDto [stringValue=" + stringValue + ", intValue=" + intValue + ", booleanValue=" + booleanValue + "]";
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.jackson.ignorenullfields;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
@JsonInclude(Include.NON_NULL)
public class MyDtoIgnoreNull {
private String stringValue;
private int intValue;
private boolean booleanValue;
public MyDtoIgnoreNull() {
super();
}
public MyDtoIgnoreNull(final String stringValue, final int intValue, final boolean booleanValue) {
super();
this.stringValue = stringValue;
this.intValue = intValue;
this.booleanValue = booleanValue;
}
// API
public String getStringValue() {
return stringValue;
}
public void setStringValue(final String stringValue) {
this.stringValue = stringValue;
}
public int getIntValue() {
return intValue;
}
public void setIntValue(final int intValue) {
this.intValue = intValue;
}
public boolean isBooleanValue() {
return booleanValue;
}
public void setBooleanValue(final boolean booleanValue) {
this.booleanValue = booleanValue;
}
}

View File

@ -1,13 +1,12 @@
package com.baeldung.jackson.deserialization.jsonalias;
package com.baeldung.jackson.multiplefields;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.baeldung.jackson.entities.Weather;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonAliasUnitTest {
public class MapMultipleFieldsToSingleFieldUnitTest {
@Test
public void givenTwoJsonFormats_whenDeserialized_thenWeatherObjectsCreated() throws Exception {

View File

@ -13,7 +13,7 @@ import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
import static junit.framework.TestCase.assertEquals;
public class JacksonStreamingAPIUnitTest {
public class StreamingAPIUnitTest {
@Test
public void givenJsonGenerator_whenAppendJsonToIt_thenGenerateJson() throws IOException {

View File

@ -0,0 +1,80 @@
package com.baeldung.jackson.unknownproperties;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
public class UnknownPropertiesUnitTest {
@Test
public final void givenNotAllFieldsHaveValuesInJson_whenDeserializingAJsonToAClass_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
final String jsonAsString = "{\"stringValue\":\"a\",\"booleanValue\":true}";
final ObjectMapper mapper = new ObjectMapper();
final MyDto readValue = mapper.readValue(jsonAsString, MyDto.class);
assertNotNull(readValue);
assertThat(readValue.getStringValue(), equalTo("a"));
assertThat(readValue.isBooleanValue(), equalTo(true));
}
// tests - json with unknown fields
@Test(expected = UnrecognizedPropertyException.class)
public final void givenJsonHasUnknownValues_whenDeserializingAJsonToAClass_thenExceptionIsThrown() throws JsonParseException, JsonMappingException, IOException {
final String jsonAsString = "{\"stringValue\":\"a\",\"intValue\":1,\"booleanValue\":true,\"stringValue2\":\"something\"}";
final ObjectMapper mapper = new ObjectMapper();
final MyDto readValue = mapper.readValue(jsonAsString, MyDto.class);
assertNotNull(readValue);
assertThat(readValue.getStringValue(), equalTo("a"));
assertThat(readValue.isBooleanValue(), equalTo(true));
assertThat(readValue.getIntValue(), equalTo(1));
}
@Test
public final void givenJsonHasUnknownValuesButJacksonIsIgnoringUnknownFields_whenDeserializing_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
final String jsonAsString = // @formatter:off
"{\"stringValue\":\"a\"," +
"\"intValue\":1," +
"\"booleanValue\":true," +
"\"stringValue2\":\"something\"}"; // @formatter:on
final ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
final MyDto readValue = mapper.readValue(jsonAsString, MyDto.class);
assertNotNull(readValue);
assertThat(readValue.getStringValue(), equalTo("a"));
assertThat(readValue.isBooleanValue(), equalTo(true));
assertThat(readValue.getIntValue(), equalTo(1));
}
@Test
public final void givenJsonHasUnknownValuesButUnknownFieldsAreIgnoredOnClass_whenDeserializing_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
final String jsonAsString = // @formatter:off
"{\"stringValue\":\"a\"," +
"\"intValue\":1," +
"\"booleanValue\":true," +
"\"stringValue2\":\"something\"}"; // @formatter:on
final ObjectMapper mapper = new ObjectMapper();
final MyDtoIgnoreUnknown readValue = mapper.readValue(jsonAsString, MyDtoIgnoreUnknown.class);
assertNotNull(readValue);
assertThat(readValue.getStringValue(), equalTo("a"));
assertThat(readValue.isBooleanValue(), equalTo(true));
assertThat(readValue.getIntValue(), equalTo(1));
}
}

View File

@ -15,8 +15,6 @@ import java.util.List;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.jackson.entities.Order;
import com.baeldung.jackson.entities.OrderLine;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
@ -37,7 +35,7 @@ public class YamlUnitTest {
@Test
public void givenYamlInput_ObjectCreated() throws JsonParseException, JsonMappingException, IOException {
Order order = mapper.readValue(new File("src/main/resources/orderInput.yaml"), Order.class);
Order order = mapper.readValue(new File("src/test/resources/yaml/orderInput.yaml"), Order.class);
assertEquals("A001", order.getOrderNo());
assertEquals(LocalDate.parse("2019-04-17", DateTimeFormatter.ISO_DATE), order.getDate());
assertEquals("Customer, Joe", order.getCustomerName());
@ -55,9 +53,9 @@ public class YamlUnitTest {
LocalDate.parse("2019-04-18", DateTimeFormatter.ISO_DATE),
"Customer, Jane",
lines);
mapper.writeValue(new File("src/main/resources/orderOutput.yaml"), order);
mapper.writeValue(new File("src/test/resources/yaml/orderOutput.yaml"), order);
File outputYaml = new File("src/main/resources/orderOutput.yaml");
File outputYaml = new File("src/test/resources/yaml/orderOutput.yaml");
assertTrue(outputYaml.exists());
}
}

View File

@ -0,0 +1,16 @@
## Jackson Conversions
This module contains articles about Jackson conversions.
### Relevant Articles:
- [Jackson Unmarshall to Collection/Array](https://www.baeldung.com/jackson-collection-array)
- [Jackson Date](https://www.baeldung.com/jackson-serialize-dates)
- [Jackson Working with Maps and Nulls](https://www.baeldung.com/jackson-map-null-values-or-null-key)
- [Jackson Decide What Fields Get Serialized/Deserialized](https://www.baeldung.com/jackson-field-serializable-deserializable-or-not)
- [XML Serialization and Deserialization with Jackson](https://www.baeldung.com/jackson-xml-serialization-and-deserialization)
- [Map Serialization and Deserialization with Jackson](https://www.baeldung.com/jackson-map)
- [How to Serialize and Deserialize Enums with Jackson](https://www.baeldung.com/jackson-serialize-enums)
- [Jackson Marshall String to JsonNode](https://www.baeldung.com/jackson-json-to-jsonnode)
- [Mapping Nested Values with Jackson](https://www.baeldung.com/jackson-nested-values)
- [Deserialize Immutable Objects with Jackson](https://www.baeldung.com/jackson-deserialize-immutable-objects)
- More articles: [[next -->]](../jackson-conversions-2)

View File

@ -0,0 +1,49 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>jackson-conversions</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jackson-conversions</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson.version}</version>
</dependency>
<!--jackson for xml -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
<build>
<finalName>jackson-conversions</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deserialization.enums;
package com.baeldung.jackson.enums.deserialization;
public class City {

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deserialization.enums;
package com.baeldung.jackson.enums.deserialization;
public enum Distance {

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deserialization.enums.customdeserializer;
package com.baeldung.jackson.enums.deserialization.customdeserializer;
public class City {

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deserialization.enums.customdeserializer;
package com.baeldung.jackson.enums.deserialization.customdeserializer;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParser;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deserialization.enums.customdeserializer;
package com.baeldung.jackson.enums.deserialization.customdeserializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deserialization.enums.jsoncreator;
package com.baeldung.jackson.enums.deserialization.jsoncreator;
public class City {

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deserialization.enums.jsoncreator;
package com.baeldung.jackson.enums.deserialization.jsoncreator;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deserialization.enums.jsonproperty;
package com.baeldung.jackson.enums.deserialization.jsonproperty;
public class City {

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deserialization.enums.jsonproperty;
package com.baeldung.jackson.enums.deserialization.jsonproperty;
import com.fasterxml.jackson.annotation.JsonProperty;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deserialization.enums.jsonvalue;
package com.baeldung.jackson.enums.deserialization.jsonvalue;
public class City {

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deserialization.enums.jsonvalue;
package com.baeldung.jackson.enums.deserialization.jsonvalue;
import com.fasterxml.jackson.annotation.JsonValue;

View File

@ -1,6 +1,6 @@
package com.baeldung.jackson.enums;
package com.baeldung.jackson.enums.serialization;
import com.baeldung.jackson.serialization.DistanceSerializer;
import com.baeldung.jackson.enums.serialization.DistanceSerializer;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
/**

View File

@ -1,8 +1,7 @@
package com.baeldung.jackson.serialization;
package com.baeldung.jackson.enums.serialization;
import java.io.IOException;
import com.baeldung.jackson.enums.Distance;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializerProvider;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.dtos.withEnum;
package com.baeldung.jackson.enums.withEnum;
public enum DistanceEnumSimple {
KILOMETER("km", 1000), MILE("miles", 1609.34), METER("meters", 1), INCH("inches", 0.0254), CENTIMETER("cm", 0.01), MILLIMETER("mm", 0.001);

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.dtos.withEnum;
package com.baeldung.jackson.enums.withEnum;
import com.fasterxml.jackson.annotation.JsonFormat;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.dtos.withEnum;
package com.baeldung.jackson.enums.withEnum;
import com.fasterxml.jackson.annotation.JsonValue;

View File

@ -1,6 +1,6 @@
package com.baeldung.jackson.dtos.withEnum;
package com.baeldung.jackson.enums.withEnum;
import com.baeldung.jackson.enums.Distance;
import com.baeldung.jackson.enums.serialization.Distance;
public class MyDtoWithEnumCustom {

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.dtos.withEnum;
package com.baeldung.jackson.enums.withEnum;
public class MyDtoWithEnumJsonFormat {

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deserialization.immutable;
package com.baeldung.jackson.immutable;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deserialization.immutable;
package com.baeldung.jackson.immutable;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;

View File

@ -1,8 +1,7 @@
package com.baeldung.jackson.entities;
package com.baeldung.jackson.map;
import java.util.Map;
import com.baeldung.jackson.serialization.MyPairDeserializer;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.entities;
package com.baeldung.jackson.map;
import com.fasterxml.jackson.annotation.JsonValue;

View File

@ -1,8 +1,7 @@
package com.baeldung.jackson.serialization;
package com.baeldung.jackson.map;
import java.io.IOException;
import com.baeldung.jackson.entities.MyPair;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.KeyDeserializer;

View File

@ -1,9 +1,8 @@
package com.baeldung.jackson.serialization;
package com.baeldung.jackson.map;
import java.io.IOException;
import java.io.StringWriter;
import com.baeldung.jackson.entities.MyPair;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;

View File

@ -0,0 +1,54 @@
package com.baeldung.jackson.mapnull;
public class MyDto {
private String stringValue;
private int intValue;
private boolean booleanValue;
public MyDto() {
super();
}
public MyDto(final String stringValue, final int intValue, final boolean booleanValue) {
super();
this.stringValue = stringValue;
this.intValue = intValue;
this.booleanValue = booleanValue;
}
// API
public String getStringValue() {
return stringValue;
}
public void setStringValue(final String stringValue) {
this.stringValue = stringValue;
}
public int getIntValue() {
return intValue;
}
public void setIntValue(final int intValue) {
this.intValue = intValue;
}
public boolean isBooleanValue() {
return booleanValue;
}
public void setBooleanValue(final boolean booleanValue) {
this.booleanValue = booleanValue;
}
//
@Override
public String toString() {
return "MyDto [stringValue=" + stringValue + ", intValue=" + intValue + ", booleanValue=" + booleanValue + "]";
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.ignore.dtos;
package com.baeldung.jackson.mapnull;
import java.io.IOException;

View File

@ -0,0 +1,54 @@
package com.baeldung.jackson.tocollection;
public class MyDto {
private String stringValue;
private int intValue;
private boolean booleanValue;
public MyDto() {
super();
}
public MyDto(final String stringValue, final int intValue, final boolean booleanValue) {
super();
this.stringValue = stringValue;
this.intValue = intValue;
this.booleanValue = booleanValue;
}
// API
public String getStringValue() {
return stringValue;
}
public void setStringValue(final String stringValue) {
this.stringValue = stringValue;
}
public int getIntValue() {
return intValue;
}
public void setIntValue(final int intValue) {
this.intValue = intValue;
}
public boolean isBooleanValue() {
return booleanValue;
}
public void setBooleanValue(final boolean booleanValue) {
this.booleanValue = booleanValue;
}
//
@Override
public String toString() {
return "MyDto [stringValue=" + stringValue + ", intValue=" + intValue + ", booleanValue=" + booleanValue + "]";
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.jackson.xml;
public class Address {
String streetNumber;
String streetName;
String city;
public String getStreetNumber() {
return streetNumber;
}
public void setStreetNumber(String streetNumber) {
this.streetNumber = streetNumber;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.jackson.xml;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import java.util.ArrayList;
import java.util.List;
@JacksonXmlRootElement(localName = "person")
public final class Person {
private String firstName;
private String lastName;
private List<String> phoneNumbers = new ArrayList<>();
private List<Address> address = new ArrayList<>();
public List<Address> getAddress() {
return address;
}
public void setAddress(List<Address> address) {
this.address = address;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List<String> getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(List<String> phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.test;
package com.baeldung.jackson.date;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals;

View File

@ -1,7 +1,8 @@
package com.baeldung.jackson.deserialization.enums;
package com.baeldung.jackson.enums.deserialization;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;

View File

@ -1,7 +1,8 @@
package com.baeldung.jackson.deserialization.enums.customdeserializer;
package com.baeldung.jackson.enums.deserialization.customdeserializer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;

View File

@ -1,7 +1,8 @@
package com.baeldung.jackson.deserialization.enums.jsoncreator;
package com.baeldung.jackson.enums.deserialization.jsoncreator;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;

View File

@ -1,7 +1,8 @@
package com.baeldung.jackson.deserialization.enums.jsonproperty;
package com.baeldung.jackson.enums.deserialization.jsonproperty;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;

View File

@ -1,7 +1,8 @@
package com.baeldung.jackson.deserialization.enums.jsonvalue;
package com.baeldung.jackson.enums.deserialization.jsonvalue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;

View File

@ -1,8 +1,9 @@
package com.baeldung.jackson.enums;
package com.baeldung.jackson.enums.serialization;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.test;
package com.baeldung.jackson.enums.serialization;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
@ -8,12 +8,12 @@ import java.io.IOException;
import org.junit.Test;
import com.baeldung.jackson.dtos.withEnum.DistanceEnumSimple;
import com.baeldung.jackson.dtos.withEnum.DistanceEnumWithJsonFormat;
import com.baeldung.jackson.dtos.withEnum.DistanceEnumWithValue;
import com.baeldung.jackson.dtos.withEnum.MyDtoWithEnumCustom;
import com.baeldung.jackson.dtos.withEnum.MyDtoWithEnumJsonFormat;
import com.baeldung.jackson.enums.Distance;
import com.baeldung.jackson.enums.withEnum.DistanceEnumSimple;
import com.baeldung.jackson.enums.withEnum.DistanceEnumWithJsonFormat;
import com.baeldung.jackson.enums.withEnum.DistanceEnumWithValue;
import com.baeldung.jackson.enums.withEnum.MyDtoWithEnumCustom;
import com.baeldung.jackson.enums.withEnum.MyDtoWithEnumJsonFormat;
import com.baeldung.jackson.enums.serialization.Distance;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.test;
package com.baeldung.jackson.field;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
@ -7,10 +7,6 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import com.baeldung.jackson.field.MyDtoAccessLevel;
import com.baeldung.jackson.field.MyDtoWithSetter;
import com.baeldung.jackson.field.MyDtoWithGetter;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deserialization.immutable;
package com.baeldung.jackson.immutable;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.deserialization;
package com.baeldung.jackson.map;
import java.io.IOException;
import java.util.HashMap;
@ -7,8 +7,6 @@ import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.jackson.entities.ClassWithAMap;
import com.baeldung.jackson.entities.MyPair;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.serialization;
package com.baeldung.jackson.map;
import java.util.HashMap;
import java.util.Map;
@ -6,7 +6,6 @@ import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.jackson.entities.MyPair;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

View File

@ -0,0 +1,109 @@
package com.baeldung.jackson.mapnull;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.PropertyFilter;
import com.fasterxml.jackson.databind.ser.PropertyWriter;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import org.junit.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
public class JacksonMapNullUnitTest {
@Test
public final void givenIgnoringMapNullValue_whenWritingMapObjectWithNullValue_thenIgnored() throws JsonProcessingException {
final ObjectMapper mapper = new ObjectMapper();
// mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
mapper.setSerializationInclusion(Include.NON_NULL);
final MyDto dtoObject1 = new MyDto();
final Map<String, MyDto> dtoMap = new HashMap<String, MyDto>();
dtoMap.put("dtoObject1", dtoObject1);
dtoMap.put("dtoObject2", null);
final String dtoMapAsString = mapper.writeValueAsString(dtoMap);
assertThat(dtoMapAsString, containsString("dtoObject1"));
assertThat(dtoMapAsString, not(containsString("dtoObject2")));
System.out.println(dtoMapAsString);
}
@Test
public final void givenIgnoringMapValueObjectWithNullField_whenWritingMapValueObjectWithNullField_thenIgnored() throws JsonProcessingException {
final ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
final MyDto dtoObject = new MyDto();
final Map<String, MyDto> dtoMap = new HashMap<String, MyDto>();
dtoMap.put("dtoObject", dtoObject);
final String dtoMapAsString = mapper.writeValueAsString(dtoMap);
assertThat(dtoMapAsString, containsString("dtoObject"));
assertThat(dtoMapAsString, not(containsString("stringValue")));
System.out.println(dtoMapAsString);
}
@Test
public final void givenAllowingMapObjectWithNullKey_whenWriting_thenCorrect() throws JsonProcessingException {
final ObjectMapper mapper = new ObjectMapper();
mapper.getSerializerProvider()
.setNullKeySerializer(new MyDtoNullKeySerializer());
final MyDto dtoObject1 = new MyDto();
dtoObject1.setStringValue("dtoObjectString1");
final MyDto dtoObject2 = new MyDto();
dtoObject2.setStringValue("dtoObjectString2");
final Map<String, MyDto> dtoMap = new HashMap<String, MyDto>();
dtoMap.put(null, dtoObject1);
dtoMap.put("obj2", dtoObject2);
final String dtoMapAsString = mapper.writeValueAsString(dtoMap);
System.out.println(dtoMapAsString);
assertThat(dtoMapAsString, containsString("\"\""));
assertThat(dtoMapAsString, containsString("dtoObjectString1"));
assertThat(dtoMapAsString, containsString("obj2"));
}
@Test
public final void givenAllowingMapObjectOneNullKey_whenWritingMapObjectWithTwoNullKeys_thenOverride() throws JsonProcessingException {
final ObjectMapper mapper = new ObjectMapper();
mapper.getSerializerProvider()
.setNullKeySerializer(new MyDtoNullKeySerializer());
final MyDto dtoObject1 = new MyDto();
dtoObject1.setStringValue("dtoObject1String");
final MyDto dtoObject2 = new MyDto();
dtoObject2.setStringValue("dtoObject2String");
final Map<String, MyDto> dtoMap = new HashMap<String, MyDto>();
dtoMap.put(null, dtoObject1);
dtoMap.put(null, dtoObject2);
final String dtoMapAsString = mapper.writeValueAsString(dtoMap);
assertThat(dtoMapAsString, not(containsString("dtoObject1String")));
assertThat(dtoMapAsString, containsString("dtoObject2String"));
System.out.println(dtoMapAsString);
}
}

View File

@ -1,70 +1,70 @@
package com.baeldung.jackson.deserialization.nested;
import static org.junit.Assert.*;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
public class DeserializeWithNestedPropertiesUnitTest {
private String SOURCE_JSON = "{\"id\":\"957c43f2-fa2e-42f9-bf75-6e3d5bb6960a\",\"name\":\"The Best Product\",\"brand\":{\"id\":\"9bcd817d-0141-42e6-8f04-e5aaab0980b6\",\"name\":\"ACME Products\",\"owner\":{\"id\":\"b21a80b1-0c09-4be3-9ebd-ea3653511c13\",\"name\":\"Ultimate Corp, Inc.\"}}}";
@Test
public void whenUsingAnnotations_thenOk() throws IOException {
Product product = new ObjectMapper().readerFor(Product.class)
.readValue(SOURCE_JSON);
assertEquals(product.getName(), "The Best Product");
assertEquals(product.getBrandName(), "ACME Products");
assertEquals(product.getOwnerName(), "Ultimate Corp, Inc.");
}
@Test
public void whenUsingJsonNode_thenOk() throws IOException {
JsonNode productNode = new ObjectMapper().readTree(SOURCE_JSON);
Product product = new Product();
product.setId(productNode.get("id")
.textValue());
product.setName(productNode.get("name")
.textValue());
product.setBrandName(productNode.get("brand")
.get("name")
.textValue());
product.setOwnerName(productNode.get("brand")
.get("owner")
.get("name")
.textValue());
assertEquals(product.getName(), "The Best Product");
assertEquals(product.getBrandName(), "ACME Products");
assertEquals(product.getOwnerName(), "Ultimate Corp, Inc.");
}
@Test
public void whenUsingDeserializerManuallyRegistered_thenOk() throws IOException {
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Product.class, new ProductDeserializer());
mapper.registerModule(module);
Product product = mapper.readValue(SOURCE_JSON, Product.class);
assertEquals(product.getName(), "The Best Product");
assertEquals(product.getBrandName(), "ACME Products");
assertEquals(product.getOwnerName(), "Ultimate Corp, Inc.");
}
@Test
public void whenUsingDeserializerAutoRegistered_thenOk() throws IOException {
ObjectMapper mapper = new ObjectMapper();
Product product = mapper.readValue(SOURCE_JSON, Product.class);
assertEquals(product.getName(), "The Best Product");
assertEquals(product.getBrandName(), "ACME Products");
assertEquals(product.getOwnerName(), "Ultimate Corp, Inc.");
}
}
package com.baeldung.jackson.nested;
import static org.junit.Assert.*;
import java.io.IOException;
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
public class DeserializeWithNestedPropertiesUnitTest {
private String SOURCE_JSON = "{\"id\":\"957c43f2-fa2e-42f9-bf75-6e3d5bb6960a\",\"name\":\"The Best Product\",\"brand\":{\"id\":\"9bcd817d-0141-42e6-8f04-e5aaab0980b6\",\"name\":\"ACME Products\",\"owner\":{\"id\":\"b21a80b1-0c09-4be3-9ebd-ea3653511c13\",\"name\":\"Ultimate Corp, Inc.\"}}}";
@Test
public void whenUsingAnnotations_thenOk() throws IOException {
Product product = new ObjectMapper().readerFor(Product.class)
.readValue(SOURCE_JSON);
assertEquals(product.getName(), "The Best Product");
assertEquals(product.getBrandName(), "ACME Products");
assertEquals(product.getOwnerName(), "Ultimate Corp, Inc.");
}
@Test
public void whenUsingJsonNode_thenOk() throws IOException {
JsonNode productNode = new ObjectMapper().readTree(SOURCE_JSON);
Product product = new Product();
product.setId(productNode.get("id")
.textValue());
product.setName(productNode.get("name")
.textValue());
product.setBrandName(productNode.get("brand")
.get("name")
.textValue());
product.setOwnerName(productNode.get("brand")
.get("owner")
.get("name")
.textValue());
assertEquals(product.getName(), "The Best Product");
assertEquals(product.getBrandName(), "ACME Products");
assertEquals(product.getOwnerName(), "Ultimate Corp, Inc.");
}
@Test
public void whenUsingDeserializerManuallyRegistered_thenOk() throws IOException {
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Product.class, new ProductDeserializer());
mapper.registerModule(module);
Product product = mapper.readValue(SOURCE_JSON, Product.class);
assertEquals(product.getName(), "The Best Product");
assertEquals(product.getBrandName(), "ACME Products");
assertEquals(product.getOwnerName(), "Ultimate Corp, Inc.");
}
@Test
public void whenUsingDeserializerAutoRegistered_thenOk() throws IOException {
ObjectMapper mapper = new ObjectMapper();
Product product = mapper.readValue(SOURCE_JSON, Product.class);
assertEquals(product.getName(), "The Best Product");
assertEquals(product.getBrandName(), "ACME Products");
assertEquals(product.getOwnerName(), "Ultimate Corp, Inc.");
}
}

View File

@ -1,55 +1,55 @@
package com.baeldung.jackson.deserialization.nested;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
@JsonDeserialize(using = ProductDeserializer.class)
public class Product {
private String id;
private String name;
private String brandName;
private String ownerName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getOwnerName() {
return ownerName;
}
public void setOwnerName(String ownerName) {
this.ownerName = ownerName;
}
@SuppressWarnings("unchecked")
@JsonProperty("brand")
private void unpackNested(Map<String, Object> brand) {
this.brandName = (String) brand.get("name");
Map<String, String> owner = (Map<String, String>) brand.get("owner");
this.ownerName = owner.get("name");
}
package com.baeldung.jackson.nested;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
@JsonDeserialize(using = ProductDeserializer.class)
public class Product {
private String id;
private String name;
private String brandName;
private String ownerName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getOwnerName() {
return ownerName;
}
public void setOwnerName(String ownerName) {
this.ownerName = ownerName;
}
@SuppressWarnings("unchecked")
@JsonProperty("brand")
private void unpackNested(Map<String, Object> brand) {
this.brandName = (String) brand.get("name");
Map<String, String> owner = (Map<String, String>) brand.get("owner");
this.ownerName = owner.get("name");
}
}

View File

@ -1,40 +1,40 @@
package com.baeldung.jackson.deserialization.nested;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
@SuppressWarnings("serial")
public class ProductDeserializer extends StdDeserializer<Product> {
public ProductDeserializer() {
this(null);
}
public ProductDeserializer(Class<?> vc) {
super(vc);
}
@Override
public Product deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
JsonNode productNode = jp.getCodec()
.readTree(jp);
Product product = new Product();
product.setId(productNode.get("id")
.textValue());
product.setName(productNode.get("name")
.textValue());
product.setBrandName(productNode.get("brand")
.get("name")
.textValue());
product.setOwnerName(productNode.get("brand")
.get("owner")
.get("name")
.textValue());
return product;
}
}
package com.baeldung.jackson.nested;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
@SuppressWarnings("serial")
public class ProductDeserializer extends StdDeserializer<Product> {
public ProductDeserializer() {
this(null);
}
public ProductDeserializer(Class<?> vc) {
super(vc);
}
@Override
public Product deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
JsonNode productNode = jp.getCodec()
.readTree(jp);
Product product = new Product();
product.setId(productNode.get("id")
.textValue());
product.setName(productNode.get("name")
.textValue());
product.setBrandName(productNode.get("brand")
.get("name")
.textValue());
product.setOwnerName(productNode.get("brand")
.get("owner")
.get("name")
.textValue());
return product;
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.jackson.test;
package com.baeldung.jackson.tocollection;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertThat;
@ -6,8 +6,6 @@ import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import com.baeldung.jackson.dtos.MyDto;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonParseException;

View File

@ -0,0 +1,51 @@
package com.baeldung.jackson.tojsonnode;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import org.junit.Test;
import java.io.IOException;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class StringToJsonNodeUnitTest {
@Test
public final void whenParsingJsonStringIntoJsonNode_thenCorrect() throws JsonParseException, IOException {
final String jsonString = "{\"k1\":\"v1\",\"k2\":\"v2\"}";
final ObjectMapper mapper = new ObjectMapper();
final JsonNode actualObj = mapper.readTree(jsonString);
assertNotNull(actualObj);
}
@Test
public final void givenUsingLowLevelDetails_whenParsingJsonStringIntoJsonNode_thenCorrect() throws JsonParseException, IOException {
final String jsonString = "{\"k1\":\"v1\",\"k2\":\"v2\"}";
final ObjectMapper mapper = new ObjectMapper();
final JsonFactory factory = mapper.getFactory();
final JsonParser parser = factory.createParser(jsonString);
final JsonNode actualObj = mapper.readTree(parser);
assertNotNull(actualObj);
}
@Test
public final void givenTheJsonNode_whenRetrievingDataFromId_thenCorrect() throws JsonParseException, IOException {
final String jsonString = "{\"k1\":\"v1\",\"k2\":\"v2\"}";
final ObjectMapper mapper = new ObjectMapper();
final JsonNode actualObj = mapper.readTree(jsonString);
// When
final JsonNode jsonNode1 = actualObj.get("k1");
assertThat(jsonNode1.textValue(), equalTo("v1"));
}
}

View File

@ -16,8 +16,6 @@ import java.util.List;
import org.junit.Test;
import com.baeldung.jackson.dtos.Address;
import com.baeldung.jackson.dtos.Person;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

Some files were not shown because too many files have changed in this diff Show More