From 4d698916eac61a4fe0e6f882fc53ddbe24005212 Mon Sep 17 00:00:00 2001 From: Unknown Date: Sun, 14 Jan 2018 23:26:02 +0900 Subject: [PATCH 1/2] Update examples --- Java-JsonPojo-Example/README.md | 30 ++-- Java-JsonPojo-Example/pom.xml | 67 ++++++++ .../java/com/howtoprogram/gson/GsonTest.java | 81 ++++++++++ .../com/howtoprogram/gson/JacksonTest.java} | 144 ++++++++++-------- 4 files changed, 240 insertions(+), 82 deletions(-) create mode 100644 Java-JsonPojo-Example/src/test/java/com/howtoprogram/gson/GsonTest.java rename Java-JsonPojo-Example/src/{main/java/com/howtoprogram/jsonpojo/JsonPojoUtils.java => test/java/com/howtoprogram/gson/JacksonTest.java} (58%) diff --git a/Java-JsonPojo-Example/README.md b/Java-JsonPojo-Example/README.md index 44e1455..8db51b1 100644 --- a/Java-JsonPojo-Example/README.md +++ b/Java-JsonPojo-Example/README.md @@ -1,7 +1,7 @@ # Java JsonPojo Examples -## 1. Import source code into Eclipse +### 1. Import source code into Eclipse Menu **File –> Import –> Maven –> Existing Maven Projects** @@ -9,29 +9,27 @@ Browse to your source code location Click **Finish** button to finish the importing -## 2. Run the example +### 2. Run the example -Open the **JsonPojoUtils.java** +Open the GsonTest.java and JacksonTest.java -**Right click -> Run As -> Java Application** or use the shortcut: **Alt+Shift+x, j** to start the main method -Source code are described in **[Convert Java Objects To JSON And Vice Versa](http://howtoprogram.xyz/2016/07/01/convert-java-objects-json-vice-versa/)** +**Right click -> Run As -> Java Application** or use the shortcut: **Alt+Shift+x, t** to start the JUnit test methods. +Source code are described in [Convert Java Objects To JSON And Vice Versa With Jackson and Gson](http://howtoprogram.xyz/2016/07/01/convert-java-objects-json-vice-versa/) -## Related articles +### Related articles -### [Simple Java REST Client Using java.net.URL package](http://howtoprogram.xyz/2016/07/02/simple-java-rest-client-using-java-net-url-package) +[Simple Java REST Client Using java.net.URL package](http://howtoprogram.xyz/2016/07/02/simple-java-rest-client-using-java-net-url-package) -### [Java REST Client Using Spring RestTemplate](http://howtoprogram.xyz/2016/07/03/java-rest-client-using-spring-resttemplate/) +[Java REST Client Using Spring RestTemplate](http://howtoprogram.xyz/2016/07/03/java-rest-client-using-spring-resttemplate/) -### [Java REST Client Using Apache Httpcomponents](http://howtoprogram.xyz/2016/07/04/java-rest-client-using-apache-httpcomponents/) +[Java REST Client Using Jersey Client](http://howtoprogram.xyz/2016/07/05/java-rest-client-using-jersey-client/) -### [Java REST Client Using Jersey Client](http://howtoprogram.xyz/2016/07/05/java-rest-client-using-jersey-client/) +[Java REST Client Using Resteasy Client](http://howtoprogram.xyz/2016/07/12/java-rest-client-using-resteasy-client/) -### [Java REST Client Using Resteasy Client](http://howtoprogram.xyz/2016/07/12/java-rest-client-using-resteasy-client/) +[Java REST Client Using Resteasy Client Proxy Framework](http://howtoprogram.xyz/2016/07/13/java-rest-client-using-resteasy-client-proxy-framework/) -### [Java REST Client Using Resteasy Client Proxy Framework](http://howtoprogram.xyz/2016/07/13/java-rest-client-using-resteasy-client-proxy-framework/) +[Java REST Client Using Apache CXF Proxy based API](http://howtoprogram.xyz/2016/07/15/java-rest-client-using-apache-cxf-proxy-based-api/) -### [Java REST Client Using Apache CXF Proxy based API](http://howtoprogram.xyz/2016/07/15/java-rest-client-using-apache-cxf-proxy-based-api/) +[Java REST Client Using Netflix Feign](http://howtoprogram.xyz/2016/07/18/java-rest-client-using-netflix-feign/) -### [Java REST Client Using Netflix Feign](http://howtoprogram.xyz/2016/07/18/java-rest-client-using-netflix-feign/) - -### [Java REST Client Using Unirest Java API](http://howtoprogram.xyz/2016/07/27/java-rest-client-using-unirest-java-api/) +[Java REST Client Using Unirest Java API](http://howtoprogram.xyz/2016/07/27/java-rest-client-using-unirest-java-api/) diff --git a/Java-JsonPojo-Example/pom.xml b/Java-JsonPojo-Example/pom.xml index c599788..22c0414 100644 --- a/Java-JsonPojo-Example/pom.xml +++ b/Java-JsonPojo-Example/pom.xml @@ -6,7 +6,13 @@ 0.0.1-SNAPSHOT + UTF-8 1.8 + 4.12 + 5.0.0 + ${junit.version}.0 + 5.0.0 + 1.0.0 @@ -15,5 +21,66 @@ jackson-databind 2.7.5 + + com.google.code.gson + gson + 2.8.1 + compile + + + org.junit.jupiter + junit-jupiter-engine + ${junit.jupiter.version} + test + + + junit + junit + ${junit.version} + test + + + org.junit.platform + junit-platform-runner + ${junit.platform.version} + test + + + org.junit.vintage + junit-vintage-engine + ${junit.vintage.version} + test + + + + + maven-compiler-plugin + 3.7.0 + + ${java.version} + ${java.version} + + + + maven-surefire-plugin + 2.19.1 + + + **/Test*.java + **/*Test.java + **/*Tests.java + **/*TestCase.java + + + + + org.junit.platform + junit-platform-surefire-provider + ${junit.platform.version} + + + + + \ No newline at end of file diff --git a/Java-JsonPojo-Example/src/test/java/com/howtoprogram/gson/GsonTest.java b/Java-JsonPojo-Example/src/test/java/com/howtoprogram/gson/GsonTest.java new file mode 100644 index 0000000..0217794 --- /dev/null +++ b/Java-JsonPojo-Example/src/test/java/com/howtoprogram/gson/GsonTest.java @@ -0,0 +1,81 @@ +package com.howtoprogram.gson; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.jupiter.api.Test; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.howtoprogram.jsonpojo.Book; + +public class GsonTest { + + @Test + public void testConvertOjectToJsonTest() { + Book milkHoneyBook = new Book(1000L, "Milk and Honey", "Rupi Kaur"); + + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + String json = gson.toJson(milkHoneyBook); + + assertTrue(json.contains("Milk and Honey")); + System.out.print(json); + } + + @Test + public void testConvertListToJsonTest() { + Book sfBook = new Book(1001L, "StrengthsFinder 2.0", "Tom Rath"); + Book pHBook = new Book(1002L, "The Power of Habit", "Charles Duhigg"); + List books = new ArrayList(); + books.add(sfBook); + books.add(pHBook); + + // Converts the list to JSON + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + String json = gson.toJson(books); + assertTrue(json.contains("StrengthsFinder 2.0")); + assertTrue(json.contains("The Power of Habit")); + + System.out.println(json); + } + + @Test + public void testConvertSetToJsonTest() { + Book litteFireBook = new Book(1001L, "Little Fires Everywhere", "Celeste Ng"); + Book leoDaVinciBook = new Book(1002L, "Leonardo da Vinci", "Walter Isaacson"); + Set books = new HashSet(); + books.add(litteFireBook); + books.add(leoDaVinciBook); + + // Converts the set to JSON + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + String json = gson.toJson(books); + assertTrue(json.contains("Little Fires Everywhere")); + assertTrue(json.contains("Leonardo da Vinci")); + + System.out.println(json); + } + + @Test + public void testConvertMapToJsonTest() { + Book eoBook = new Book(1l, "Extreme Ownership", "Jocko Willink"); + Book lopBook = new Book(2l, "The 48 Laws of Power", "Robert Greene"); + Map booksMap = new HashMap(); + booksMap.put(eoBook.getId(), eoBook); + booksMap.put(lopBook.getId(), lopBook); + + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + String json = gson.toJson(booksMap); + + assertTrue(json.contains("Extreme Ownership")); + assertTrue(json.contains("The 48 Laws of Power")); + System.out.println(json); + } + +} diff --git a/Java-JsonPojo-Example/src/main/java/com/howtoprogram/jsonpojo/JsonPojoUtils.java b/Java-JsonPojo-Example/src/test/java/com/howtoprogram/gson/JacksonTest.java similarity index 58% rename from Java-JsonPojo-Example/src/main/java/com/howtoprogram/jsonpojo/JsonPojoUtils.java rename to Java-JsonPojo-Example/src/test/java/com/howtoprogram/gson/JacksonTest.java index 6d736cd..04f2210 100644 --- a/Java-JsonPojo-Example/src/main/java/com/howtoprogram/jsonpojo/JsonPojoUtils.java +++ b/Java-JsonPojo-Example/src/test/java/com/howtoprogram/gson/JacksonTest.java @@ -1,4 +1,7 @@ -package com.howtoprogram.jsonpojo; +package com.howtoprogram.gson; + +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.File; import java.io.IOException; @@ -8,48 +11,36 @@ import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.howtoprogram.jsonpojo.Book; -public class JsonPojoUtils { - - public static void main(String[] args) { - // JSON to object - toObject(); - toList(); - toArray(); - - // Object to JSON - toJSON(); - collectionToJSON(); - // Working with file - serializeToFile(); - readFromFile(); - // collectionToJSONPrettyPrint(); - mapToJson(); - } +public class JacksonTest { /** * Converts a JSON string to a {@link Book} object + * + * @throws IOException + * @throws JsonMappingException + * @throws JsonParseException */ - public static void toObject() { + @Test + public void testConvertJsonToObject() throws Exception { String json = "{\"id\":2,\"name\":\"Thinking in Java\",\"author\":\"Bruce Eckel\"}"; // create Jackson ObjectMapper ObjectMapper mapper = new ObjectMapper(); - try { - // Converts JSON string to Java object - Book book = mapper.readValue(json, Book.class); - - System.out.println(book); - - } catch (JsonProcessingException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } + // Converts JSON string to Java object + Book book = mapper.readValue(json, Book.class); + assertEquals(2, book.getId().longValue()); + assertEquals("Thinking in Java", book.getName()); + assertEquals("Bruce Eckel", book.getAuthor()); } /** @@ -113,63 +104,69 @@ public static void toJSON() { /** * Converts a list of {@link Book} to JSON + * + * @throws JsonProcessingException */ - public static void mapToJson() { - Book book1 = new Book(1l, "Java How To Program", "Paul Deitel"); - Book book2 = new Book(2l, "Thinking in Java", "Bruce Eckel"); + @Test + public void convertMapToJsonTest() throws JsonProcessingException { + Book ilBook = new Book(1l, "The Immortalists", "Chloe Benjamin"); + Book gdrmBook = new Book(2l, "The Girl Who Drank the Moon", "Kelly Barnhill"); Map bookMap = new HashMap(); - bookMap.put(book1.getId(), book1); - bookMap.put(book2.getId(), book2); + bookMap.put(ilBook.getId(), ilBook); + bookMap.put(gdrmBook.getId(), gdrmBook); - try { - // Converts the list to JSON - ObjectMapper mapper = new ObjectMapper(); - String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(bookMap); - // json = mapper.writeValueAsString(bookMap); - System.out.println(json); - } catch (JsonProcessingException e) { - e.printStackTrace(); - } + // Converts the list to JSON + ObjectMapper mapper = new ObjectMapper(); + String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(bookMap); + + assertTrue(json.contains(ilBook.getName())); + assertTrue(json.contains(gdrmBook.getName())); + + System.out.println(json); } /** * Converts a list of {@link Book} to JSON + * + * @throws JsonProcessingException */ - public static void collectionToJSON() { - Book book1 = new Book(1l, "Java How To Program", "Paul Deitel"); - Book book2 = new Book(2l, "Thinking in Java", "Bruce Eckel"); + @Test + public void convertCollectionToJsonTest() throws JsonProcessingException { + Book h2prBook = new Book(1l, "Java How To Program", "Paul Deitel"); + Book thinkJavaBook = new Book(2l, "Thinking in Java", "Bruce Eckel"); List books = new ArrayList(); - books.add(book1); - books.add(book2); + books.add(h2prBook); + books.add(thinkJavaBook); + + // Converts the list to JSON + ObjectMapper mapper = new ObjectMapper(); + String json = mapper.writeValueAsString(books); + + assertTrue(json.contains(h2prBook.getName())); + assertTrue(json.contains(thinkJavaBook.getName())); + + System.out.println(json); - try { - // Converts the list to JSON - ObjectMapper mapper = new ObjectMapper(); - String json = mapper.writeValueAsString(books); - System.out.println(json); - } catch (JsonProcessingException e) { - e.printStackTrace(); - } } /** * Converts a list of {@link Book} to JSON + * + * @throws JsonProcessingException */ - public static void collectionToJSONPrettyPrint() { + @Test + public void collectionToJSONPrettyPrintTest() throws JsonProcessingException { Book book1 = new Book(1l, "Java How To Program", "Paul Deitel"); Book book2 = new Book(2l, "Thinking in Java", "Bruce Eckel"); List books = new ArrayList(); books.add(book1); books.add(book2); - try { - // Converts the list to JSON - ObjectMapper mapper = new ObjectMapper(); - String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(books); - System.out.println(json); - } catch (JsonProcessingException e) { - e.printStackTrace(); - } + // Converts the list to JSON + ObjectMapper mapper = new ObjectMapper(); + String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(books); + System.out.println(json); + } /** @@ -198,6 +195,21 @@ public static void serializeToFile() { } } + @Test + public void testConvertObjectToJSON() throws JsonProcessingException { + Book shBook = new Book(1l, "Sour Heart", "Jenny Zhang"); + + // Converts the shBook to JSON + ObjectMapper mapper = new ObjectMapper(); + // String json = + // mapper.writerWithDefaultPrettyPrinter().writeValueAsString(shBook); + String json = mapper.writeValueAsString(shBook); + assertTrue(json.contains("Sour Heart")); + assertTrue(json.contains("Jenny Zhang")); + System.out.println(json); + + } + /** * Read JSON content from the file: d:/books.json and convert to an array. * Assume that the d:/books.json was exist. From e7cc7651044ceda2b59ea3315e5cdf249935af0a Mon Sep 17 00:00:00 2001 From: Unknown Date: Sun, 14 Jan 2018 23:39:30 +0900 Subject: [PATCH 2/2] update pojo --- Java-JsonPojo-Example/pom.xml | 7 + .../java/com/howtoprogram/jsonpojo/Book.java | 146 ++++++++++-------- 2 files changed, 86 insertions(+), 67 deletions(-) diff --git a/Java-JsonPojo-Example/pom.xml b/Java-JsonPojo-Example/pom.xml index 22c0414..67da9e6 100644 --- a/Java-JsonPojo-Example/pom.xml +++ b/Java-JsonPojo-Example/pom.xml @@ -21,6 +21,13 @@ jackson-databind 2.7.5 + + + com.fasterxml.jackson.datatype + jackson-datatype-jdk8 + 2.9.0 + + com.google.code.gson gson diff --git a/Java-JsonPojo-Example/src/main/java/com/howtoprogram/jsonpojo/Book.java b/Java-JsonPojo-Example/src/main/java/com/howtoprogram/jsonpojo/Book.java index ceb43f2..95e1a6c 100644 --- a/Java-JsonPojo-Example/src/main/java/com/howtoprogram/jsonpojo/Book.java +++ b/Java-JsonPojo-Example/src/main/java/com/howtoprogram/jsonpojo/Book.java @@ -1,75 +1,87 @@ package com.howtoprogram.jsonpojo; +import java.time.LocalDate; +import java.util.Date; + +import com.fasterxml.jackson.annotation.JsonInclude; + +import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; public class Book { - private Long id; - private String name; - private String author; - - - public Book() { - super(); - } - - public Book(Long id, String name, String author) { - super(); - this.id = id; - this.name = name; - this.author = author; - } - - /** - * @return the id - */ - public Long getId() { - return id; - } - - /** - * @param id the id to set - */ - public void setId(Long id) { - this.id = id; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name the name to set - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the author - */ - public String getAuthor() { - return author; - } - - /** - * @param author the author to set - */ - public void setAuthor(String author) { - this.author = author; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "Book [id=" + id + ", name=" + name + ", author=" + author + "]"; - } + private Long id; + private String name; + private String author; + + @JsonInclude(NON_NULL) + private LocalDate pubDate; + @JsonInclude(NON_NULL) + private Date copyrightDate; + + public Book() { + super(); + } + + public Book(Long id, String name, String author) { + super(); + this.id = id; + this.name = name; + this.author = author; + } + + /** + * @return the id + */ + public Long getId() { + return id; + } + + /** + * @param id + * the id to set + */ + public void setId(Long id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the author + */ + public String getAuthor() { + return author; + } + + /** + * @param author + * the author to set + */ + public void setAuthor(String author) { + this.author = author; + } + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "Book [id=" + id + ", name=" + name + ", author=" + author + "]"; + } }