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文件路径。