Part 1: read from String, File and InputStream
This commit is contained in:
@@ -0,0 +1,49 @@
|
|||||||
|
package com.ankurm.jackson3.part1objectmapper;
|
||||||
|
|
||||||
|
import tools.jackson.databind.json.JsonMapper;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.File;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Post: Jackson ObjectMapper Guide — https://ankurm.com/jackson-objectmapper-guide/
|
||||||
|
* Section: "Deserialising JSON to Java Objects"
|
||||||
|
*
|
||||||
|
* Reading from a String, a File and an InputStream.
|
||||||
|
*
|
||||||
|
* The post also shows readValue(new URL(...), ...). That overload is deliberately
|
||||||
|
* NOT reproduced here: it performs a live network call, which would make this
|
||||||
|
* example non-reproducible. The InputStream form below is what a real HTTP client
|
||||||
|
* hands you anyway.
|
||||||
|
*/
|
||||||
|
public class B02ReadJson {
|
||||||
|
|
||||||
|
public record Article(Long articleId, String title, List<String> tags) { }
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
JsonMapper mapper = JsonMapper.builder().build();
|
||||||
|
|
||||||
|
String json = "{\"articleId\":1,\"title\":\"Jackson Deep Dive\",\"tags\":[\"java\",\"json\"]}";
|
||||||
|
|
||||||
|
// 1. Read from a String
|
||||||
|
Article fromString = mapper.readValue(json, Article.class);
|
||||||
|
System.out.println("from String : " + fromString.title());
|
||||||
|
|
||||||
|
// 2. Read from a File
|
||||||
|
File file = File.createTempFile("article", ".json");
|
||||||
|
Files.writeString(file.toPath(), json);
|
||||||
|
Article fromFile = mapper.readValue(file, Article.class);
|
||||||
|
System.out.println("from File : " + fromFile.articleId());
|
||||||
|
|
||||||
|
// 3. Read from an InputStream
|
||||||
|
try (var in = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8))) {
|
||||||
|
Article fromStream = mapper.readValue(in, Article.class);
|
||||||
|
System.out.println("from Stream : " + fromStream.tags());
|
||||||
|
}
|
||||||
|
|
||||||
|
file.deleteOnExit();
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user