[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
-3
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)
-14
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>
@@ -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);
}
}
+14
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)
+67
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>
@@ -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;
@@ -1,4 +1,4 @@
package com.baeldung.jackson.entities;
package com.baeldung.jackson.csv;
import java.math.BigDecimal;
@@ -1,4 +1,4 @@
package com.baeldung.jackson.mixin;
package com.baeldung.jackson.csv;
import java.math.BigDecimal;
@@ -1,4 +1,4 @@
package com.baeldung.jackson.deserialization.dynamicobject;
package com.baeldung.jackson.dynamicobject;
import java.util.LinkedHashMap;
import java.util.Map;
@@ -1,4 +1,4 @@
package com.baeldung.jackson.deserialization.dynamicobject;
package com.baeldung.jackson.dynamicobject;
import com.fasterxml.jackson.databind.JsonNode;
@@ -1,4 +1,4 @@
package com.baeldung.jackson.deserialization.dynamicobject;
package com.baeldung.jackson.dynamicobject;
import java.util.Map;
@@ -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;
@@ -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 + "]";
}
}
@@ -1,4 +1,4 @@
package com.baeldung.jackson.dtos.ignore;
package com.baeldung.jackson.unknownproperties;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@@ -1,4 +1,4 @@
package com.baeldung.jackson.dtos.ignore;
package com.baeldung.jackson.unknownproperties;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@@ -1,4 +1,4 @@
package com.baeldung.jackson.entities;
package com.baeldung.jackson.yaml;
import java.time.LocalDate;
import java.util.ArrayList;
@@ -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 + "]";
}
}
@@ -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"));
}
@@ -1,4 +1,4 @@
package com.baeldung.jackson.deserialization.dynamicobject;
package com.baeldung.jackson.dynamicobject;
import static org.assertj.core.api.Assertions.assertThat;
@@ -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);
}
}
@@ -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 + "]";
}
}
@@ -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;
}
}
@@ -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 {
@@ -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 {
@@ -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));
}
}

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