javax.json 패키지는 개체 모델 API를 제공합니다. JSON을 처리합니다. 개체 모델 API는 JSON 개체 및 배열 구조에 대해 변경할 수 없는 개체 모델을 제공하는 고급 API입니다. 이러한 JSON 구조는 JsonObject 를 사용하여 개체 모델로 나타낼 수 있습니다. 및 JsonArray 인터페이스. JsonGenerator 를 사용할 수 있습니다. 스트리밍 방식으로 JSON 데이터를 출력에 쓰는 인터페이스. JsonGenerator.PRETTY_PRINTING JSON을 예쁘게 생성하기 위한 설정 속성입니다.
아래 예에서 예쁜 인쇄 JSON을 구현할 수 있습니다.
예
import java.io.*;
import java.util.*;
import javax.json.*;
import javax.json.stream.*;
public class JSONPrettyPrintTest {
public static void main(String args[]) {
String jsonString = "{\"name\":\"Raja Ramesh\",\"age\":\"35\",\"salary\":\"40000\"}";
StringWriter sw = new StringWriter();
try {
JsonReader jsonReader = Json.createReader(new StringReader(jsonString));
JsonObject jsonObj = jsonReader.readObject();
Map<String, Object> map = new HashMap<>();
map.put(JsonGenerator.PRETTY_PRINTING, true);
JsonWriterFactory writerFactory = Json.createWriterFactory(map);
JsonWriter jsonWriter = writerFactory.createWriter(sw);
jsonWriter.writeObject(jsonObj);
jsonWriter.close();
} catch(Exception e) {
e.printStackTrace();
}
String prettyPrint = sw.toString();
System.out.println(prettyPrint); // pretty print JSON
}
} 출력
{
"name": "Raja Ramesh",
"age": "35",
"salary": "40000"
}