首页 > 文章列表 > 如何在Java中从JSON对象中获取不同类型的值?

如何在Java中从JSON对象中获取不同类型的值?

JSON解析 Java中的JSON库 获取JSON对象中的值
341 2023-08-20

一个JSONObject是一个无序的键值对的集合,并解析文本字符串以生成类似于map的对象。一个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