Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

Pretty Print JSON ด้วย org.json Library ใน Java

JSON เป็น Data Exchange Format แบบ Lightweight, Text-based, Language-independent JSONObject Parse Text จาก String ผลลัพธ์เป็น Map-like Object Package org.json Implement JSON Encoders/Decoders ใน Java รองรับ Convert ระหว่าง JSON, XML, HTTP Headers, Cookies, CDL

Pretty-print JSON ด้วยเมธอด toString(int indentFactor) ของ org.json.JSONObject โดย indentFactor = จำนวน Space ต่อ Indentation Level

Syntax

public String toString(int indentFactor) throws JSONException

ตัวอย่าง: Pretty Print JSON

import org.json.*;

public class JSONPrettyPrintTest {
    public static void main(String[] args) throws JSONException {
        String json = "{"
            + " \"Name\": \"Jai\","
            + " \"Age\": 25,"
            + " \"Salary\": 25000.00"
        + "}";
        
        JSONObject jsonObj = new JSONObject(json);
        System.out.println("Pretty Print of JSON:");
        System.out.println(jsonObj.toString(4));  // Indent 4 Spaces
    }
}

ผลลัพธ์

Pretty Print of JSON:
{
    "Salary": 25000,
    "Age": 25,
    "Name": "Jai"
}

Dependency (Maven):

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20231013</version>
</dependency>

Class หลัก: JSONObject, JSONArray, JSONTokener, CDL (CSV↔JSON)