Part 1: write to String, File and pretty-printed String
This commit is contained in:
@@ -0,0 +1,39 @@
|
|||||||
|
package com.ankurm.jackson3.part1objectmapper;
|
||||||
|
|
||||||
|
import tools.jackson.databind.json.JsonMapper;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Post: Jackson ObjectMapper Guide — https://ankurm.com/jackson-objectmapper-guide/
|
||||||
|
* Section: "Serialising Java Objects to JSON"
|
||||||
|
*
|
||||||
|
* Every write target: String, File, and pretty-printed String.
|
||||||
|
*/
|
||||||
|
public class B01WriteJson {
|
||||||
|
|
||||||
|
public record Article(Long articleId, String title, List<String> tags) { }
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
JsonMapper mapper = JsonMapper.builder().build();
|
||||||
|
Article article = new Article(1L, "Jackson Deep Dive", List.of("java", "json"));
|
||||||
|
|
||||||
|
// 1. Write to a String
|
||||||
|
String jsonOutput = mapper.writeValueAsString(article);
|
||||||
|
System.out.println(jsonOutput);
|
||||||
|
|
||||||
|
// 2. Write to a File
|
||||||
|
File target = File.createTempFile("article", ".json");
|
||||||
|
mapper.writeValue(target, article);
|
||||||
|
System.out.println("file : " + Files.readString(target.toPath()));
|
||||||
|
|
||||||
|
// 3. Pretty-printed output
|
||||||
|
String pretty = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(article);
|
||||||
|
System.out.println("pretty :");
|
||||||
|
System.out.println(pretty);
|
||||||
|
|
||||||
|
target.deleteOnExit();
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user