java json总结 读取json文件或者把对象写入到json文件里面

这段摘要包含了博客的关键信息,忽略信息技术无关的内容,提供核心价值。
来源:https://www.cnblogs.com/gongchenglion/p/5892967.html
### 将 JSON 对象写入 txt 文件Java 中,可以使用 `org.json` 库来操作 JSON 对象将其写入 txt 文件。以下是示例代码: ```java import org.json.JSONObject; import java.io.FileWriter; import java.io.IOException; public class WriteJsonToTxt { public static void main(String[] args) { // 创建一个 JSON 对象 JSONObject jsonObject = new JSONObject(); jsonObject.put("name", "John"); jsonObject.put("age", 30); jsonObject.put("city", "New York"); try (FileWriter fileWriter = new FileWriter("data.txt")) { // 将 JSON 对象转换为字符串写入文件 fileWriter.write(jsonObject.toString()); System.out.println("JSON 对象已成功写入文件。"); } catch (IOException e) { e.printStackTrace(); } } } ``` ### 从 txt 文件读取内容解析为 JSON 对象 同样使用 `org.json` 库,以下是从 txt 文件读取内容解析为 JSON 对象的示例代码: ```java import org.json.JSONObject; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class ReadJsonFromTxt { public static void main(String[] args) { StringBuilder jsonContent = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) { String line; while ((line = reader.readLine()) != null) { jsonContent.append(line); } // 将读取的内容解析为 JSON 对象 JSONObject jsonObject = new JSONObject(jsonContent.toString()); System.out.println("从文件读取JSON 对象:"); System.out.println(jsonObject.toString(2)); } catch (IOException e) { e.printStackTrace(); } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值