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

เข้ารหัส (Encode) JSON Object ใน Java

JSONObject เป็นคลาสย่อยของ java.util.HashMap ไม่มีลำดับ แต่สามารถใช้ LinkedHashMap ร่วมกับ JSONValue.toJSONString(map) เพื่อรักษาลำดับการแทรกได้

ตัวอย่าง 1: ใช้ HashMap กับ JSONObject

import java.util.*;
import org.json.simple.JSONObject;

public class JSONEncodingTest {
    public static void main(String[] args) {
        Map<Object, Object> dataMap = new HashMap<>();
        dataMap.put("Name", "Adithya");
        dataMap.put("Age", 25);
        dataMap.put("Salary", 25000.00);
        dataMap.put("Employee Id", 115);
        dataMap.put("Company", "TutorialsPoint");
        
        JSONObject jsonObj = new JSONObject(dataMap);
        System.out.print("Encoding a JSON object: ");
        System.out.print(jsonObj);
    }
}

ผลลัพธ์

Encoding a JSON object: {"Salary":25000.0,"Employee id":115,"Company":"TutorialsPoint","Age":25,"Name":"Adithya"}

ตัวอย่าง 2: ใช้ JSONObject โดยตรงและเขียนด้วย StringWriter

import java.io.*;
import org.json.simple.*;

public class JSONEncodingTest1 {
    public static void main(String[] args) throws IOException {
        JSONObject obj = new JSONObject();
        obj.put("Name", "Jai");
        obj.put("Mobile_Number", 995998480);
        obj.put("Bank_Balance", 50000.00);
        obj.put("Is_A_SelfEmployee", false);
        
        StringWriter out = new StringWriter();
        obj.writeJSONString(out);
        String jsonText = out.toString();
        System.out.print(jsonText);
    }
}

ผลลัพธ์

{"Is_A_SelfEmployee":false,"Bank_Balance":50000.0,"Mobile_Number":995998480,"Name":"Jai"}

เมธอดสำคัญ: writeJSONString() เขียน JSON ไปยัง Writer, escape() หลีกเลี่ยงอักขระพิเศษ