Java 中 JSON 字符串与 JSON 对象的转换240
在 Java 中,JSON(JavaScript Object Notation)是一种广泛使用的轻量级数据交换格式。它通常以字符串的形式出现,但有时也需要将其转换为 JSON 对象以进行处理或操作。
JSON 字符串转 JSON 对象
以下是如何在 Java 中将 JSON 字符串转换为 JSON 对象:```java
import ;
public class JsonStringToObject {
public static void main(String[] args) {
// JSON 字符串
String jsonString = "{name:John Doe,age:30,occupation:Developer}";
// 使用 Gson 库转换 JSON 字符串
Gson gson = new Gson();
JsonObject jsonObject = (jsonString, );
// 访问 JSON 对象的属性
String name = ("name").getAsString();
int age = ("age").getAsInt();
String occupation = ("occupation").getAsString();
// 打印 JSON 对象属性
("Name: " + name);
("Age: " + age);
("Occupation: " + occupation);
}
}
```
JSON 对象转 JSON 字符串
以下是如何在 Java 中将 JSON 对象转换为 JSON 字符串:```java
import ;
public class JsonObjectToString {
public static void main(String[] args) {
// JSON 对象
JsonObject jsonObject = new JsonObject();
("name", new JsonPrimitive("John Doe"));
("age", new JsonPrimitive(30));
("occupation", new JsonPrimitive("Developer"));
// 使用 Gson 库转换 JSON 对象
Gson gson = new Gson();
String jsonString = (jsonObject);
// 打印转换后的 JSON 字符串
(jsonString);
}
}
```
在 Java 中,可以使用 Google Gson 库或其他 JSON 解析库轻松地将 JSON 字符串转换为 JSON 对象,反之亦然。这对于处理和操作 JSON 数据非常有用。
2024-11-12
下一篇:Java 正则表达式中的特殊字符
Java方法栈日志的艺术:从错误定位到性能优化的深度指南
https://www.shuihudhg.cn/133725.html
PHP 获取本机端口的全面指南:实践与技巧
https://www.shuihudhg.cn/133724.html
Python内置函数:从核心原理到高级应用,精通Python编程的基石
https://www.shuihudhg.cn/133723.html
Java Stream转数组:从基础到高级,掌握高性能数据转换的艺术
https://www.shuihudhg.cn/133722.html
深入解析:基于Java数组构建简易ATM机系统,从原理到代码实践
https://www.shuihudhg.cn/133721.html
热门文章
Java中数组赋值的全面指南
https://www.shuihudhg.cn/207.html
JavaScript 与 Java:二者有何异同?
https://www.shuihudhg.cn/6764.html
判断 Java 字符串中是否包含特定子字符串
https://www.shuihudhg.cn/3551.html
Java 字符串的切割:分而治之
https://www.shuihudhg.cn/6220.html
Java 输入代码:全面指南
https://www.shuihudhg.cn/1064.html