Skip to content

Commit 3b8ee23

Browse files
author
eugenp
committed
minor example work
1 parent b3fbba5 commit 3b8ee23

2 files changed

Lines changed: 23 additions & 44 deletions

File tree

‎jackson/src/test/java/org/baeldung/jackson/try1/COrder.java‎

Lines changed: 0 additions & 32 deletions
This file was deleted.
Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,42 @@
11
package org.baeldung.jackson.try1;
22

3-
import static org.junit.Assert.assertNotNull;
4-
53
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;
89

910
import org.junit.Test;
1011

1112
import com.fasterxml.jackson.core.JsonParseException;
12-
import com.fasterxml.jackson.core.type.TypeReference;
1313
import com.fasterxml.jackson.databind.JsonMappingException;
1414
import com.fasterxml.jackson.databind.ObjectMapper;
15-
import com.google.common.base.Charsets;
16-
import com.google.common.io.Resources;
1715

1816
public class JacksonTryUnitTest {
1917

2018
@Test
2119
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+
}
2422

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+
}
2736

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();
2940
}
3041

3142
}

0 commit comments

Comments
 (0)