如何在 Java 中從 JSON 物件獲取不同型別的值?


JSONObject 是一種無序名稱/值對集合,可從 String 解析文字以為產生類似對映的物件。JSONObject 有一些重要的方法顯示不同型別的值,如使用與鍵字串關聯的字串值的 getString() 方法,使用與鍵關聯的整數值的 getInt() 方法,使用與鍵關聯的雙精度值的 getDouble() 方法,使用與鍵關聯的布林值的 getBoolean() 方法。

示例

import org.json.*;
public class JSONObjectTypeValuesTest {
   public static void main(String[] args) throws JSONException {
      JSONObject jsonObj = new JSONObject(
         "{" +
            "Name : Adithya," +
            "Age : 22, " +
            "Salary: 10000.00, " +
            "IsSelfEmployee: false " +
         "}"
      );
      System.out.println(jsonObj.getString("Name")); // returns string
      System.out.println(jsonObj.getInt("Age")); // returns int
      System.out.println(jsonObj.getDouble("Salary")); // returns double
      System.out.println(jsonObj.getBoolean("IsSelfEmployee")); // returns true/false
   }
}

輸出

Adithya
22
10000.0
false

更新於: 14-Sep-2023

30K+ 瀏覽量

開始你的 職業生涯

透過完成課程獲得認證

開始
廣告