|
1 | 1 | package org.baeldung.jackson.try1; |
2 | 2 |
|
3 | | -import static org.junit.Assert.assertNotNull; |
4 | | - |
5 | 3 | import java.io.IOException; |
6 | | -import java.net.URL; |
7 | | -import java.util.Collection; |
| 4 | +import java.nio.ByteBuffer; |
| 5 | +import java.nio.charset.Charset; |
| 6 | +import java.nio.charset.StandardCharsets; |
| 7 | +import java.nio.file.Files; |
| 8 | +import java.nio.file.Paths; |
8 | 9 |
|
9 | 10 | import org.junit.Test; |
10 | 11 |
|
11 | 12 | import com.fasterxml.jackson.core.JsonParseException; |
12 | | -import com.fasterxml.jackson.core.type.TypeReference; |
13 | 13 | import com.fasterxml.jackson.databind.JsonMappingException; |
14 | 14 | import com.fasterxml.jackson.databind.ObjectMapper; |
15 | | -import com.google.common.base.Charsets; |
16 | | -import com.google.common.io.Resources; |
17 | 15 |
|
18 | 16 | public class JacksonTryUnitTest { |
19 | 17 |
|
20 | 18 | @Test |
21 | 19 | public final void whenDeserializing_thenCorrect() throws JsonParseException, JsonMappingException, IOException { |
22 | | - final URL url = Resources.getResource("example2.json"); |
23 | | - final String jsonAsString = Resources.toString(url, Charsets.UTF_8); |
| 20 | + printJsonFromFile("/opt/git/github/eugenp/tutorials/jackson/src/main/resources/example1.json"); |
| 21 | + } |
24 | 22 |
|
25 | | - final Collection<COrder> readValues = new ObjectMapper().readValue(jsonAsString, new TypeReference<Collection<COrder>>() { |
26 | | - }); |
| 23 | + // |
| 24 | + |
| 25 | + public static void printJsonFromFile(final String fileName) { |
| 26 | + System.out.println("-----------------"); |
| 27 | + final ObjectMapper mapper = new ObjectMapper(); |
| 28 | + try { |
| 29 | + final Object json = mapper.readValue(readFile(fileName, StandardCharsets.UTF_8), Object.class); |
| 30 | + System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json)); |
| 31 | + } catch (final IOException e) { |
| 32 | + e.printStackTrace(); |
| 33 | + } |
| 34 | + System.out.println("-----------------"); |
| 35 | + } |
27 | 36 |
|
28 | | - assertNotNull(readValues); |
| 37 | + static String readFile(final String path, final Charset encoding) throws IOException { |
| 38 | + final byte[] encoded = Files.readAllBytes(Paths.get(path)); |
| 39 | + return encoding.decode(ByteBuffer.wrap(encoded)).toString(); |
29 | 40 | } |
30 | 41 |
|
31 | 42 | } |
0 commit comments