请用java写一段程序,读取json文件中的数据并显示,同时给出json文件内容
时间: 2024-02-06 19:11:03 浏览: 61
好的,以下是一个简单的Java程序,可以读取JSON文件并将其内容打印出来:
```java
import java.io.FileReader;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class ReadJsonFile {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("example.json"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
long age = (Long) jsonObject.get("age");
JSONArray hobbies = (JSONArray) jsonObject.get("hobbies");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Hobbies: ");
for (Object hobby : hobbies) {
System.out.println("- " + hobby);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这里假设我们有一个名为 "example.json" 的JSON文件,其内容如下:
```json
{
"name": "John",
"age": 25,
"hobbies": ["reading", "swimming", "traveling"]
}
```
当我们运行上面的Java程序时,它将读取"example.json"文件并将其内容打印出来,输出如下:
```
Name: John
Age: 25
Hobbies:
- reading
- swimming
- traveling
```
阅读全文