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

แปลง JSON String เป็น JSON Object ใน Java

JSON ย่อมาจาก JavaScript Object Notation ใช้สำหรับ โอนและเก็บข้อมูล JSONObject แปลงข้อความจาก String เป็นอ็อบเจกต์แบบ Map JSONArray แปลงเป็นอ็อบเจกต์แบบเวกเตอร์

ตัวอย่าง 1: แปลง JSON Array String เป็น JSONArray

import org.json.JSONObject;
import org.json.JSONArray;

public class StringToJSONTest {
    public static void main(String args[]) {
        String str = "[{\"No\":\"1\",\"Name\":\"Adithya\"},{\"No\":\"2\",\"Name\":\"Jai\"},{\"No\":\"3\",\"Name\":\"Raja\"}]";
        JSONArray array = new JSONArray(str);
        
        for (int i = 0; i < array.length(); i++) {
            JSONObject object = array.getJSONObject(i);
            System.out.println(object.getString("No"));
            System.out.println(object.getString("Name"));
        }
    }
}

ผลลัพธ์

1
Adithya
2
Jai
3
Raja

ตัวอย่าง 2: แปลง JSON Object String เป็น JSONObject

import org.json.*;

public class StringToJsonObjectTest {
    public static void main(String[] args) {
        String str = "{\"name\":\"Raja\",\"technology\":\"Java\"}";
        JSONObject json = new JSONObject(str);
        System.out.println(json.toString());
        String tech = json.getString("technology");
        System.out.println(tech);
    }
}

ผลลัพธ์

{"name":"Raja","technology":"Java"}
Java

สรุป: ใช้ Constructor new JSONObject(String) หรือ new JSONArray(String) ตรงๆ