Merge branch 'master' into master
This commit is contained in:
@@ -10,4 +10,7 @@
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
*.ear
|
||||
|
||||
# Files
|
||||
/src/main/resources/orderOutput.yaml
|
||||
@@ -8,3 +8,4 @@ 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)
|
||||
|
||||
@@ -22,6 +22,20 @@
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- YAML -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
||||
<artifactId>jackson-dataformat-yaml</artifactId>
|
||||
<version>2.9.8</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Allow use of LocalDate -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||
<version>2.9.8</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<!-- test scoped -->
|
||||
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.baeldung.jackson.entities;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class Order {
|
||||
private String orderNo;
|
||||
private LocalDate date;
|
||||
private String customerName;
|
||||
private List<OrderLine> orderLines;
|
||||
|
||||
public Order() {
|
||||
|
||||
}
|
||||
|
||||
public Order(String orderNo, LocalDate date, String customerName, List<OrderLine> orderLines) {
|
||||
super();
|
||||
this.orderNo = orderNo;
|
||||
this.date = date;
|
||||
this.customerName = customerName;
|
||||
this.orderLines = orderLines;
|
||||
}
|
||||
|
||||
public String getOrderNo() {
|
||||
return orderNo;
|
||||
}
|
||||
|
||||
public void setOrderNo(String orderNo) {
|
||||
this.orderNo = orderNo;
|
||||
}
|
||||
|
||||
public LocalDate getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(LocalDate date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
public String getCustomerName() {
|
||||
return customerName;
|
||||
}
|
||||
|
||||
public void setCustomerName(String customerName) {
|
||||
this.customerName = customerName;
|
||||
}
|
||||
|
||||
public List<OrderLine> getOrderLines() {
|
||||
if (orderLines == null) {
|
||||
orderLines = new ArrayList<>();
|
||||
}
|
||||
return orderLines;
|
||||
}
|
||||
|
||||
public void setOrderLines(List<OrderLine> orderLines) {
|
||||
if (orderLines == null) {
|
||||
orderLines = new ArrayList<>();
|
||||
}
|
||||
this.orderLines = orderLines;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Order [orderNo=" + orderNo + ", date=" + date + ", customerName=" + customerName + ", orderLines=" + orderLines + "]";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.baeldung.jackson.entities;
|
||||
|
||||
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 + "]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.baeldung.jackson.node;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
|
||||
public class JsonNodeIterator {
|
||||
|
||||
private static final String NEW_LINE = "\n";
|
||||
private static final String FIELD_DELIMITER = ": ";
|
||||
private static final String ARRAY_PREFIX = "- ";
|
||||
private static final String YAML_PREFIX = " ";
|
||||
|
||||
public String toYaml(JsonNode root) {
|
||||
StringBuilder yaml = new StringBuilder();
|
||||
processNode(root, yaml, 0);
|
||||
return yaml.toString();
|
||||
}
|
||||
|
||||
private void processNode(JsonNode jsonNode, StringBuilder yaml, int depth) {
|
||||
if (jsonNode.isValueNode()) {
|
||||
yaml.append(jsonNode.asText());
|
||||
}
|
||||
else if (jsonNode.isArray()) {
|
||||
for (JsonNode arrayItem : jsonNode) {
|
||||
appendNodeToYaml(arrayItem, yaml, depth, true);
|
||||
}
|
||||
}
|
||||
else if (jsonNode.isObject()) {
|
||||
appendNodeToYaml(jsonNode, yaml, depth, false);
|
||||
}
|
||||
}
|
||||
|
||||
private void appendNodeToYaml(JsonNode node, StringBuilder yaml, int depth, boolean isArrayItem) {
|
||||
Iterator<Entry<String, JsonNode>> fields = node.fields();
|
||||
boolean isFirst = true;
|
||||
while (fields.hasNext()) {
|
||||
Entry<String, JsonNode> jsonField = fields.next();
|
||||
addFieldNameToYaml(yaml, jsonField.getKey(), depth, isArrayItem && isFirst);
|
||||
processNode(jsonField.getValue(), yaml, depth+1);
|
||||
isFirst = false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void addFieldNameToYaml(StringBuilder yaml, String fieldName, int depth, boolean isFirstInArray) {
|
||||
if (yaml.length()>0) {
|
||||
yaml.append(NEW_LINE);
|
||||
int requiredDepth = (isFirstInArray) ? depth-1 : depth;
|
||||
for(int i = 0; i < requiredDepth; i++) {
|
||||
yaml.append(YAML_PREFIX);
|
||||
}
|
||||
if (isFirstInArray) {
|
||||
yaml.append(ARRAY_PREFIX);
|
||||
}
|
||||
}
|
||||
yaml.append(fieldName);
|
||||
yaml.append(FIELD_DELIMITER);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
orderNo: A001
|
||||
date: 2019-04-17
|
||||
customerName: Customer, Joe
|
||||
orderLines:
|
||||
- item: No. 9 Sprockets
|
||||
quantity: 12
|
||||
unitPrice: 1.23
|
||||
- item: Widget (10mm)
|
||||
quantity: 4
|
||||
unitPrice: 3.45
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.jackson.node;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class ExampleStructure {
|
||||
private static ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
static JsonNode getExampleRoot() throws IOException {
|
||||
InputStream exampleInput = ExampleStructure.class.getClassLoader()
|
||||
.getResourceAsStream("node_example.json");
|
||||
JsonNode rootNode = mapper.readTree(exampleInput);
|
||||
return rootNode;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.jackson.node;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
|
||||
public class JsonNodeIteratorUnitTest {
|
||||
|
||||
private JsonNodeIterator onTest = new JsonNodeIterator();
|
||||
private static String expectedYaml = "name: \n" +
|
||||
" first: Tatu\n" +
|
||||
" last: Saloranta\n" +
|
||||
"title: Jackson founder\n" +
|
||||
"company: FasterXML\n" +
|
||||
"pets: \n" +
|
||||
"- type: dog\n" +
|
||||
" number: 1\n" +
|
||||
"- type: fish\n" +
|
||||
" number: 50";
|
||||
|
||||
@Test
|
||||
public void givenANodeTree_whenIteratingSubNodes_thenWeFindExpected() throws IOException {
|
||||
final JsonNode rootNode = ExampleStructure.getExampleRoot();
|
||||
|
||||
String yaml = onTest.toYaml(rootNode);
|
||||
System.out.println(yaml.toString());
|
||||
|
||||
assertEquals(expectedYaml, yaml);
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.jackson.node;
|
||||
|
||||
public class NodeBean {
|
||||
private int id;
|
||||
private String name;
|
||||
|
||||
public NodeBean() {
|
||||
}
|
||||
|
||||
public NodeBean(int id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package com.baeldung.jackson.node;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.containsString;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.FileReader;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
public class NodeOperationUnitTest {
|
||||
private static ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@Test
|
||||
public void givenAnObject_whenConvertingIntoNode_thenCorrect() {
|
||||
final NodeBean fromValue = new NodeBean(2016, "baeldung.com");
|
||||
|
||||
final JsonNode node = mapper.valueToTree(fromValue);
|
||||
|
||||
assertEquals(2016, node.get("id")
|
||||
.intValue());
|
||||
assertEquals("baeldung.com", node.get("name")
|
||||
.textValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenANode_whenWritingOutAsAJsonString_thenCorrect() throws IOException {
|
||||
final String pathToTestFile = "node_to_json_test.json";
|
||||
final char[] characterBuffer = new char[50];
|
||||
|
||||
final JsonNode node = mapper.createObjectNode();
|
||||
((ObjectNode) node).put("id", 2016);
|
||||
((ObjectNode) node).put("name", "baeldung.com");
|
||||
|
||||
try (FileWriter outputStream = new FileWriter(pathToTestFile)) {
|
||||
mapper.writeValue(outputStream, node);
|
||||
}
|
||||
|
||||
try (FileReader inputStreamForAssertion = new FileReader(pathToTestFile)) {
|
||||
inputStreamForAssertion.read(characterBuffer);
|
||||
}
|
||||
final String textContentOfTestFile = new String(characterBuffer);
|
||||
|
||||
assertThat(textContentOfTestFile, containsString("2016"));
|
||||
assertThat(textContentOfTestFile, containsString("baeldung.com"));
|
||||
|
||||
Files.delete(Paths.get(pathToTestFile));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenANode_whenConvertingIntoAnObject_thenCorrect() throws JsonProcessingException {
|
||||
final JsonNode node = mapper.createObjectNode();
|
||||
((ObjectNode) node).put("id", 2016);
|
||||
((ObjectNode) node).put("name", "baeldung.com");
|
||||
|
||||
final NodeBean toValue = mapper.treeToValue(node, NodeBean.class);
|
||||
|
||||
assertEquals(2016, toValue.getId());
|
||||
assertEquals("baeldung.com", toValue.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenANode_whenAddingIntoATree_thenCorrect() throws IOException {
|
||||
final JsonNode rootNode = ExampleStructure.getExampleRoot();
|
||||
final ObjectNode addedNode = ((ObjectNode) rootNode).putObject("address");
|
||||
addedNode.put("city", "Seattle")
|
||||
.put("state", "Washington")
|
||||
.put("country", "United States");
|
||||
|
||||
assertFalse(rootNode.path("address")
|
||||
.isMissingNode());
|
||||
assertEquals("Seattle", rootNode.path("address")
|
||||
.path("city")
|
||||
.textValue());
|
||||
assertEquals("Washington", rootNode.path("address")
|
||||
.path("state")
|
||||
.textValue());
|
||||
assertEquals("United States", rootNode.path("address")
|
||||
.path("country")
|
||||
.textValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenANode_whenModifyingIt_thenCorrect() throws IOException {
|
||||
final String newString = "{\"nick\": \"cowtowncoder\"}";
|
||||
final JsonNode newNode = mapper.readTree(newString);
|
||||
|
||||
final JsonNode rootNode = ExampleStructure.getExampleRoot();
|
||||
((ObjectNode) rootNode).set("name", newNode);
|
||||
|
||||
assertFalse(rootNode.path("name")
|
||||
.path("nick")
|
||||
.isMissingNode());
|
||||
assertEquals("cowtowncoder", rootNode.path("name")
|
||||
.path("nick")
|
||||
.textValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenANode_whenRemovingFromATree_thenCorrect() throws IOException {
|
||||
final JsonNode rootNode = ExampleStructure.getExampleRoot();
|
||||
((ObjectNode) rootNode).remove("company");
|
||||
|
||||
assertTrue(rootNode.path("company")
|
||||
.isMissingNode());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.baeldung.jackson.yaml;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
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;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
|
||||
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator.Feature;
|
||||
|
||||
public class YamlUnitTest {
|
||||
private ObjectMapper mapper;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
mapper = new ObjectMapper(new YAMLFactory().disable(Feature.WRITE_DOC_START_MARKER));
|
||||
mapper.findAndRegisterModules();
|
||||
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenYamlInput_ObjectCreated() throws JsonParseException, JsonMappingException, IOException {
|
||||
Order order = mapper.readValue(new File("src/main/resources/orderInput.yaml"), Order.class);
|
||||
assertEquals("A001", order.getOrderNo());
|
||||
assertEquals(LocalDate.parse("2019-04-17", DateTimeFormatter.ISO_DATE), order.getDate());
|
||||
assertEquals("Customer, Joe", order.getCustomerName());
|
||||
assertEquals(2, order.getOrderLines()
|
||||
.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenYamlObject_FileWritten() throws JsonGenerationException, JsonMappingException, IOException {
|
||||
List<OrderLine> lines = new ArrayList<>();
|
||||
lines.add(new OrderLine("Copper Wire (200ft)", 1, new BigDecimal(50.67).setScale(2, RoundingMode.HALF_UP)));
|
||||
lines.add(new OrderLine("Washers (1/4\")", 24, new BigDecimal(.15).setScale(2, RoundingMode.HALF_UP)));
|
||||
Order order = new Order(
|
||||
"B-9910",
|
||||
LocalDate.parse("2019-04-18", DateTimeFormatter.ISO_DATE),
|
||||
"Customer, Jane",
|
||||
lines);
|
||||
mapper.writeValue(new File("src/main/resources/orderOutput.yaml"), order);
|
||||
|
||||
File outputYaml = new File("src/main/resources/orderOutput.yaml");
|
||||
assertTrue(outputYaml.exists());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"name": {
|
||||
"first": "Tatu",
|
||||
"last": "Saloranta"
|
||||
},
|
||||
"title": "Jackson founder",
|
||||
"company": "FasterXML",
|
||||
"pets": [
|
||||
{
|
||||
"type": "dog",
|
||||
"number": 1
|
||||
},
|
||||
{
|
||||
"type": "fish",
|
||||
"number": 50
|
||||
}
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user