This commit is contained in:
Dassi Orleando
2017-10-25 06:05:09 +01:00
98 changed files with 1218 additions and 337 deletions
+3
View File
@@ -11,3 +11,6 @@
- [String Search Algorithms for Large Texts](http://www.baeldung.com/java-full-text-search-algorithms)
- [Test a Linked List for Cyclicity](http://www.baeldung.com/java-linked-list-cyclicity)
- [Binary Search Algorithm in Java](http://www.baeldung.com/java-binary-search)
- [Bubble Sort in Java](http://www.baeldung.com/java-bubble-sort)
- [Introduction to JGraphT](http://www.baeldung.com/jgrapht)
- [Introduction to Minimax Algorithm](http://www.baeldung.com/java-minimax-algorithm)
@@ -0,0 +1,22 @@
package com.baeldung.algorithms.editdistance;
public class EditDistanceBase {
public static int costOfSubstitution(char a, char b) {
if (a == b) {
return 0;
}
return 1;
}
public static int min(int... numbers) {
int min = Integer.MAX_VALUE;
for (int x : numbers) {
if (x < min)
min = x;
}
return min;
}
}
@@ -0,0 +1,25 @@
package com.baeldung.algorithms.editdistance;
public class EditDistanceDynamicProgramming extends EditDistanceBase {
public static int calculate(String x, String y) {
int[][] dp = new int[x.length() + 1][y.length() + 1];
for (int i = 0; i <= x.length(); i++) {
for (int j = 0; j <= y.length(); j++) {
if (i == 0)
dp[i][j] = j;
else if (j == 0)
dp[i][j] = i;
else {
dp[i][j] = min(dp[i - 1][j - 1] + costOfSubstitution(x.charAt(i - 1), y.charAt(j - 1)), dp[i - 1][j] + 1, dp[i][j - 1] + 1);
}
}
}
return dp[x.length()][y.length()];
}
}
@@ -0,0 +1,20 @@
package com.baeldung.algorithms.editdistance;
public class EditDistanceRecursive extends EditDistanceBase {
public static int calculate(String x, String y) {
if (x.isEmpty())
return y.length();
if (y.isEmpty())
return x.length();
int substitution = calculate(x.substring(1), y.substring(1)) + costOfSubstitution(x.charAt(0), y.charAt(0));
int insertion = calculate(x, y.substring(1)) + 1;
int deletion = calculate(x.substring(1), y) + 1;
return min(substitution, insertion, deletion);
}
}
@@ -1,92 +0,0 @@
package algorithms;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.algorithms.mcts.montecarlo.MonteCarloTreeSearch;
import com.baeldung.algorithms.mcts.montecarlo.State;
import com.baeldung.algorithms.mcts.montecarlo.UCT;
import com.baeldung.algorithms.mcts.tictactoe.Board;
import com.baeldung.algorithms.mcts.tictactoe.Position;
import com.baeldung.algorithms.mcts.tree.Tree;
public class MCTSTest {
Tree gameTree;
MonteCarloTreeSearch mcts;
@Before
public void initGameTree() {
gameTree = new Tree();
mcts = new MonteCarloTreeSearch();
}
@Test
public void givenStats_whenGetUCTForNode_thenUCTMatchesWithManualData() {
double uctValue = 15.79;
assertEquals(UCT.uctValue(600, 300, 20), uctValue, 0.01);
}
@Test
public void giveninitBoardState_whenGetAllPossibleStates_thenNonEmptyList() {
State initState = gameTree.getRoot().getState();
List<State> possibleStates = initState.getAllPossibleStates();
assertTrue(possibleStates.size() > 0);
}
@Test
public void givenEmptyBoard_whenPerformMove_thenLessAvailablePossitions() {
Board board = new Board();
int initAvailablePositions = board.getEmptyPositions().size();
board.performMove(Board.P1, new Position(1, 1));
int availablePositions = board.getEmptyPositions().size();
assertTrue(initAvailablePositions > availablePositions);
}
@Test
public void givenEmptyBoard_whenSimulateInterAIPlay_thenGameDraw() {
Board board = new Board();
int player = Board.P1;
int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE;
for (int i = 0; i < totalMoves; i++) {
board = mcts.findNextMove(board, player);
if (board.checkStatus() != -1) {
break;
}
player = 3 - player;
}
int winStatus = board.checkStatus();
assertEquals(winStatus, Board.DRAW);
}
@Test
public void givenEmptyBoard_whenLevel1VsLevel3_thenLevel3WinsOrDraw() {
Board board = new Board();
MonteCarloTreeSearch mcts1 = new MonteCarloTreeSearch();
mcts1.setLevel(1);
MonteCarloTreeSearch mcts3 = new MonteCarloTreeSearch();
mcts3.setLevel(3);
int player = Board.P1;
int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE;
for (int i = 0; i < totalMoves; i++) {
if (player == Board.P1)
board = mcts3.findNextMove(board, player);
else
board = mcts1.findNextMove(board, player);
if (board.checkStatus() != -1) {
break;
}
player = 3 - player;
}
int winStatus = board.checkStatus();
assertTrue(winStatus == Board.DRAW || winStatus == Board.P1);
}
}
@@ -0,0 +1,21 @@
package com.baeldung.algorithms.editdistance;
import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.Collection;
public class EditDistanceDataProvider {
@Parameters
public static Collection<Object[]> getLists() {
return Arrays.asList(new Object[][] {
{ "", "", 0 },
{ "ago", "", 3 },
{ "", "do", 2 },
{ "abc", "adc", 1 },
{ "peek", "pesek", 1 },
{ "sunday", "saturday", 3 }
});
}
}
@@ -0,0 +1,31 @@
package com.baeldung.algorithms.editdistance;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(Parameterized.class)
public class EditDistanceTest extends EditDistanceDataProvider {
String x;
String y;
int result;
public EditDistanceTest(String a, String b, int res) {
super();
x = a;
y = b;
result = res;
}
@Test
public void testEditDistance_RecursiveImplementation() {
Assert.assertEquals(result, EditDistanceRecursive.calculate(x, y));
}
@Test
public void testEditDistance_givenDynamicProgrammingImplementation() {
Assert.assertEquals(result, EditDistanceDynamicProgramming.calculate(x, y));
}
}
+2
View File
@@ -1 +1,3 @@
## Relevant articles:
[Introduction to Animal Sniffer Maven Plugin](http://www.baeldung.com/maven-animal-sniffer)
+3
View File
@@ -1 +1,4 @@
## Relevant articles:
- [Advanced Querying in Apache Cayenne](http://www.baeldung.com/apache-cayenne-query)
- [Introduction to Apache Cayenne ORM](http://www.baeldung.com/apache-cayenne-orm)
+3
View File
@@ -1,2 +1,5 @@
## Relevant Articles:
- [Introduction to Apache CXF Aegis Data Binding](http://www.baeldung.com/aegis-data-binding-in-apache-cxf)
- [Apache CXF Support for RESTful Web Services](http://www.baeldung.com/apache-cxf-rest-api)
- [A Guide to Apache CXF with Spring](http://www.baeldung.com/apache-cxf-with-spring)
- [Introduction to Apache CXF](http://www.baeldung.com/introduction-to-apache-cxf)
+44
View File
@@ -0,0 +1,44 @@
<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>
<groupId>com.baeldung</groupId>
<artifactId>apache-spark</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>apache-spark</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.spark/spark-core_2.10 -->
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.10</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,53 @@
package com.baeldung;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.*;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import scala.Tuple2;
public class WordCount {
private static final Pattern SPACE = Pattern.compile(" ");
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.err.println("Usage: JavaWordCount <file>");
System.exit(1);
}
SparkConf sparkConf = new SparkConf().setAppName("JavaWordCount").setMaster("local");
JavaSparkContext ctx = new JavaSparkContext(sparkConf);
JavaRDD<String> lines = ctx.textFile(args[0], 1);
JavaRDD<String> words = lines.flatMap(s -> Arrays.asList(SPACE.split(s)).iterator());
JavaPairRDD<String, Integer> ones = words.mapToPair(
new PairFunction<String, String, Integer>() {
@Override
public Tuple2<String, Integer> call(String s) {
return new Tuple2<>(s, 1);
}
});
JavaPairRDD<String, Integer> counts = ones.reduceByKey(
new Function2<Integer, Integer, Integer>() {
@Override
public Integer call(Integer i1, Integer i2) {
return i1 + i2;
}
});
List<Tuple2<String, Integer>> output = counts.collect();
for (Tuple2<?, ?> tuple : output) {
System.out.println(tuple._1() + ": " + tuple._2());
}
ctx.stop();
}
}
@@ -0,0 +1,3 @@
Hello from Baeldung
Keep Learning Spark
Bye from Baeldung
+3 -1
View File
@@ -1 +1,3 @@
## Relevant articles:
### Relevant Articles:
- [A Guide to Java Bytecode Manipulation with ASM](http://www.baeldung.com/java-asm)
+2
View File
@@ -1 +1,3 @@
## Relevant articles:
- [Introduction to Atomix](http://www.baeldung.com/atomix)
+3
View File
@@ -1,3 +1,6 @@
### Relevant articles
- [AWS Lambda Using DynamoDB With Java](http://www.baeldung.com/aws-lambda-dynamodb-java)
- [AWS S3 with Java](http://www.baeldung.com/aws-s3-java)
- [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda)
+4
View File
@@ -13,3 +13,7 @@ and a BODY Payload like {"id": 1,"name": "World"}
and we will get a return code of 201 and the response: Hello, World - if the transform() method from Application class is uncommented and the process() method is commented
or return code of 201 and the response: {"id": 10,"name": "Hello, World"} - if the transform() method from Application class is commented and the process() method is uncommented
## Relevant articles:
- [Apache Camel with Spring Boot](http://www.baeldung.com/apache-camel-spring-boot)
@@ -0,0 +1,74 @@
package com.baeldung.array;
import java.util.Arrays;
public class ArrayInitializer {
public static int[] initializeArrayInLoop() {
int array[] = new int[5];
for (int i = 0; i < array.length; i++)
array[i] = i + 2;
return array;
}
public static int[][] initializeMultiDimensionalArrayInLoop() {
int array[][] = new int[2][5];
for (int i = 0; i < 2; i++)
for (int j = 0; j < 5; j++)
array[i][j] = j + 1;
return array;
}
public static String[] initializeArrayAtTimeOfDeclarationMethod1() {
String array[] = new String[] { "Toyota", "Mercedes", "BMW", "Volkswagen", "Skoda" };
return array;
}
public static int[] initializeArrayAtTimeOfDeclarationMethod2() {
int[] array = new int[] { 1, 2, 3, 4, 5 };
return array;
}
public static int[] initializeArrayAtTimeOfDeclarationMethod3() {
int array[] = { 1, 2, 3, 4, 5 };
return array;
}
public static long[] initializeArrayUsingArraysFill() {
long array[] = new long[5];
Arrays.fill(array, 30);
return array;
}
public static int[] initializeArrayRangeUsingArraysFill() {
int array[] = new int[5];
Arrays.fill(array, 0, 3, -50);
return array;
}
public static int[] initializeArrayUsingArraysCopy() {
int array[] = { 1, 2, 3, 4, 5 };
int[] copy = Arrays.copyOf(array, 5);
return copy;
}
public static int[] initializeLargerArrayUsingArraysCopy() {
int array[] = { 1, 2, 3, 4, 5 };
int[] copy = Arrays.copyOf(array, 6);
return copy;
}
public static int[] initializeArrayUsingArraysSetAll() {
int[] array = new int[20];
for (int i = 0; i < 20; i++) {
Arrays.setAll(array, p -> {
if (p > 9)
return 0;
else
return p;
});
}
return array;
}
}
@@ -0,0 +1,68 @@
package com.baeldung.array;
import static com.baeldung.array.ArrayInitializer.initializeArrayAtTimeOfDeclarationMethod1;
import static com.baeldung.array.ArrayInitializer.initializeArrayAtTimeOfDeclarationMethod2;
import static com.baeldung.array.ArrayInitializer.initializeArrayAtTimeOfDeclarationMethod3;
import static com.baeldung.array.ArrayInitializer.initializeArrayInLoop;
import static com.baeldung.array.ArrayInitializer.initializeArrayRangeUsingArraysFill;
import static com.baeldung.array.ArrayInitializer.initializeArrayUsingArraysCopy;
import static com.baeldung.array.ArrayInitializer.initializeArrayUsingArraysFill;
import static com.baeldung.array.ArrayInitializer.initializeArrayUsingArraysSetAll;
import static com.baeldung.array.ArrayInitializer.initializeLargerArrayUsingArraysCopy;
import static com.baeldung.array.ArrayInitializer.initializeMultiDimensionalArrayInLoop;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Test;
public class ArrayInitializerTest {
@Test
public void whenInitializeArrayInLoop_thenCorrect() {
assertArrayEquals(new int[] { 2, 3, 4, 5, 6 }, initializeArrayInLoop());
}
@Test
public void whenInitializeMultiDimensionalArrayInLoop_thenCorrect() {
assertArrayEquals(new int[][] { { 1, 2, 3, 4, 5 }, { 1, 2, 3, 4, 5 } }, initializeMultiDimensionalArrayInLoop());
}
@Test
public void whenInitializeArrayAtTimeOfDeclarationMethod1_thenCorrect() {
assertArrayEquals(new String[] { "Toyota", "Mercedes", "BMW", "Volkswagen", "Skoda" }, initializeArrayAtTimeOfDeclarationMethod1());
}
@Test
public void whenInitializeArrayAtTimeOfDeclarationMethod2_thenCorrect() {
assertArrayEquals(new int[] { 1, 2, 3, 4, 5 }, initializeArrayAtTimeOfDeclarationMethod2());
}
@Test
public void whenInitializeArrayAtTimeOfDeclarationMethod3_thenCorrect() {
assertArrayEquals(new int[] { 1, 2, 3, 4, 5 }, initializeArrayAtTimeOfDeclarationMethod3());
}
@Test
public void whenInitializeArrayUsingArraysFill_thenCorrect() {
assertArrayEquals(new long[] { 30, 30, 30, 30, 30 }, initializeArrayUsingArraysFill());
}
@Test
public void whenInitializeArrayRangeUsingArraysFill_thenCorrect() {
assertArrayEquals(new int[] { -50, -50, -50, 0, 0 }, initializeArrayRangeUsingArraysFill());
}
@Test
public void whenInitializeArrayRangeUsingArraysCopy_thenCorrect() {
assertArrayEquals(new int[] { 1, 2, 3, 4, 5 }, initializeArrayUsingArraysCopy());
}
@Test
public void whenInitializeLargerArrayRangeUsingArraysCopy_thenCorrect() {
assertArrayEquals(new int[] { 1, 2, 3, 4, 5, 0 }, initializeLargerArrayUsingArraysCopy());
}
@Test
public void whenInitializeLargerArrayRangeUsingArraysSetAll_thenCorrect() {
assertArrayEquals(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, initializeArrayUsingArraysSetAll());
}
}
+3 -2
View File
@@ -1,3 +1,4 @@
### Relevant Articles:
[Introduction to Drools](http://www.baeldung.com/drools)
[Drools Using Rules from Excel Files](http://www.baeldung.com/drools-excel)
- [Introduction to Drools](http://www.baeldung.com/drools)
- [Drools Using Rules from Excel Files](http://www.baeldung.com/drools-excel)
- [Drools Using Rules from Excel Files](http://www.baeldung.com/drools-excel)
+2
View File
@@ -5,4 +5,6 @@ This is the implementation of a [spring-hypermedia-api][1] client using Feign.
[1]: https://github.com/eugenp/spring-hypermedia-api
### Relevant Articles:
- [Intro to Feign](http://www.baeldung.com/intro-to-feign)
- [Introduction to SLF4J](http://www.baeldung.com/slf4j-with-log4j2-logback)
+2
View File
@@ -1 +1,3 @@
## Relevant articles:
- [Introduction to GraphQL](http://www.baeldung.com/graphql)
+1
View File
@@ -1,3 +1,4 @@
### Relevant articles:
- [New Stream, Comparator and Collector Functionality in Guava 21](http://www.baeldung.com/guava-21-new)
- [New in Guava 21 common.util.concurrent](http://www.baeldung.com/guava-21-util-concurrent)
- [Zipping Collections in Java](http://www.baeldung.com/java-collections-zip)
@@ -1,3 +1,4 @@
### Relevant Articles:
- [Cachable Static Assets with Spring MVC](http://www.baeldung.com/cachable-static-assets-with-spring-mvc)
- [Minification of JS and CSS Assets with Maven](http://www.baeldung.com/maven-minification-of-js-and-css-assets)
- [Serve Static Resources with Spring](http://www.baeldung.com/spring-mvc-static-resources)
+2
View File
@@ -20,3 +20,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [HttpAsyncClient Tutorial](http://www.baeldung.com/httpasyncclient-tutorial)
- [HttpClient 4 Tutorial](http://www.baeldung.com/httpclient-guide)
- [Advanced HttpClient Configuration](http://www.baeldung.com/httpclient-advanced-config)
- [HttpClient 4 – Do Not Follow Redirects](http://www.baeldung.com/httpclient-stop-follow-redirect)
- [HttpClient 4 – Setting a Custom User-Agent](http://www.baeldung.com/httpclient-user-agent-header)
+7
View File
@@ -28,3 +28,10 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [A Guide to Optional with Jackson](http://www.baeldung.com/jackson-optional)
- [Map Serialization and Deserialization with Jackson](http://www.baeldung.com/jackson-map)
- [Jackson Streaming API](http://www.baeldung.com/jackson-streaming-api)
- [Jackson – JsonMappingException (No serializer found for class)](http://www.baeldung.com/jackson-jsonmappingexception)
- [How To Serialize Enums as JSON Objects with Jackson](http://www.baeldung.com/jackson-serialize-enums)
- [Jackson – Marshall String to JsonNode](http://www.baeldung.com/jackson-json-to-jsonnode)
- [Ignore Null Fields with Jackson](http://www.baeldung.com/jackson-ignore-null-fields)
- [Jackson – Unmarshall to Collection/Array](http://www.baeldung.com/jackson-collection-array)
- [Jackson – Change Name of Field](http://www.baeldung.com/jackson-name-of-property)
- [Serialize Only Fields that meet a Custom Criteria with Jackson](http://www.baeldung.com/jackson-serialize-field-custom-criteria)
+1 -1
View File
@@ -129,7 +129,7 @@
<properties>
<!-- marshalling -->
<jackson.version>2.9.0</jackson.version>
<jackson.version>2.9.2</jackson.version>
<!-- util -->
<guava.version>19.0</guava.version>
@@ -0,0 +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.");
}
}
@@ -0,0 +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");
}
}
@@ -0,0 +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;
}
}

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