minor example work

This commit is contained in:
eugenp 2014-01-02 02:48:17 +02:00
parent b3fbba5aba
commit 3b8ee23512
2 changed files with 23 additions and 44 deletions

View File

@ -1,32 +0,0 @@
package org.baeldung.jackson.try1;
public class COrder {
private String name;
private String detail;
//
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getDetail() {
return detail;
}
public void setDetail(final String detail) {
this.detail = detail;
}
//
@Override
public String toString() {
return "COrder [name=" + name + ", detail=" + detail + ", getClass()=" + getClass() + ", hashCode()=" + hashCode() + ", toString()=" + super.toString() + "]";
}
}

View File

@ -1,31 +1,42 @@
package org.baeldung.jackson.try1; package org.baeldung.jackson.try1;
import static org.junit.Assert.assertNotNull;
import java.io.IOException; import java.io.IOException;
import java.net.URL; import java.nio.ByteBuffer;
import java.util.Collection; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.junit.Test; import org.junit.Test;
import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
public class JacksonTryUnitTest { public class JacksonTryUnitTest {
@Test @Test
public final void whenDeserializing_thenCorrect() throws JsonParseException, JsonMappingException, IOException { public final void whenDeserializing_thenCorrect() throws JsonParseException, JsonMappingException, IOException {
final URL url = Resources.getResource("example2.json"); printJsonFromFile("/opt/git/github/eugenp/tutorials/jackson/src/main/resources/example1.json");
final String jsonAsString = Resources.toString(url, Charsets.UTF_8); }
final Collection<COrder> readValues = new ObjectMapper().readValue(jsonAsString, new TypeReference<Collection<COrder>>() { //
});
assertNotNull(readValues); public static void printJsonFromFile(final String fileName) {
System.out.println("-----------------");
final ObjectMapper mapper = new ObjectMapper();
try {
final Object json = mapper.readValue(readFile(fileName, StandardCharsets.UTF_8), Object.class);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json));
} catch (final IOException e) {
e.printStackTrace();
}
System.out.println("-----------------");
}
static String readFile(final String path, final Charset encoding) throws IOException {
final byte[] encoded = Files.readAllBytes(Paths.get(path));
return encoding.decode(ByteBuffer.wrap(encoded)).toString();
} }
} }