共計 1337 個字符,預計需要花費 4 分鐘才能閱讀完成。
Java 可以使用許多庫來讀取和解析 JSON 文件,其中最常用的是 JSON.org 和 Jackson 庫。以下是使用這兩個庫的示例代碼:
- 使用 JSON.org 庫:
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
public class ReadJsonFileExample {public static void main(String[] args) {
try {
// 讀取 JSON 文件
JSONTokener tokener = new JSONTokener(new FileReader("example.json"));
JSONObject jsonObject = new JSONObject(tokener);
// 解析 JSON 對象
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
JSONArray hobbies = jsonObject.getJSONArray("hobbies");
// 輸出解析結果
System.out.println("Name:" + name);
System.out.println("Age:" + age);
System.out.println("Hobbies:" + hobbies);
} catch (Exception e) {e.printStackTrace();
}
}
}
- 使用 Jackson 庫:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ReadJsonFileExample {public static void main(String[] args) {
try {
// 創建 ObjectMapper 對象
ObjectMapper objectMapper = new ObjectMapper();
// 讀取 JSON 文件
JsonNode rootNode = objectMapper.readTree(new File("example.json"));
// 解析 JSON 對象
String name = rootNode.get("name").asText();
int age = rootNode.get("age").asInt();
JsonNode hobbiesNode = rootNode.get("hobbies");
// 輸出解析結果
System.out.println("Name:" + name);
System.out.println("Age:" + age);
System.out.println("Hobbies:" + hobbiesNode);
} catch (Exception e) {e.printStackTrace();
}
}
}
以上示例代碼演示了如何讀取名為 ”example.json” 的 JSON 文件,并從中解析出相關的屬性值。請注意,你需要將代碼中的 ”example.json” 替換為實際的 JSON 文件路徑。
丸趣 TV 網 – 提供最優質的資源集合!
正文完
發表至: Java
2023-12-21