Jackson API เป็น Java-based Library แปลง Java Objects ↔ JSON เร็วกว่า API อื่น ใช้ Memory น้อย เหมาะ Large Objects ประมวลผล JSON 3 วิธี: Streaming API, Tree Model, Data Binding
Pretty Print JSON ด้วย writerWithDefaultPrettyPrinter() ของ ObjectMapper Factory Method สร้าง ObjectWriter ที่ Serialize ด้วย Default Pretty Printer สำหรับ Indentation
Syntax
public ObjectWriter writerWithDefaultPrettyPrinter()
ตัวอย่าง: Pretty Print JSON
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class PrettyPrintJsonJacksonTest {
public static void main(String[] args) throws IOException {
String data = "{\"Age\":30,\"Technologies\":[\"Java\",\"Spark\",\"Python\"],\"Name\":\"Adithya\"}";
ObjectMapper mapper = new ObjectMapper();
Object json = mapper.readValue(data, Object.class);
String jsonStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
System.out.println(jsonStr);
}
}
ผลลัพธ์
{
"Age" : 30,
"Technologies" : [ "Java", "Spark", "Python" ],
"Name" : "Adithya"
}
วิธีอื่น:
mapper.enable(SerializationFeature.INDENT_OUTPUT)- เปิด Indent Globalmapper.writer(new DefaultPrettyPrinter())- Custom PrettyPrinter
Dependency (Maven):
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>