hutool中String转json
时间: 2023-11-28 11:05:34 浏览: 53
在hutool中,可以使用`JSONUtil.parseObj(obj)`将对象转换为JSON字符串,其中的`obj`可以是任何Java对象,包括字符串。
以下是一个示例代码:
```java
import cn.hutool.json.JSONUtil;
public class Example {
public static void main(String[] args) {
String str = "Hello World!";
String jsonStr = JSONUtil.toJsonStr(str);
System.out.println(jsonStr);
}
}
```
输出结果为:
```
"Hello World!"
```
其中的双引号表示这是一个字符串类型的JSON值。如果需要将字符串解析为JSON对象,则可以使用`JSONUtil.parseObj(jsonStr)`方法。
相关问题
hutool的String转json
Hutool 提供了一个 `JSONUtil` 工具类,可以将字符串转换为 JSON 对象。
示例代码:
```java
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
public class Test {
public static void main(String[] args) {
String jsonStr = "{\"name\":\"张三\",\"age\":18,\"gender\":\"male\"}";
JSONObject json = JSONUtil.parseObj(jsonStr);
System.out.println(json.get("name"));
System.out.println(json.get("age"));
System.out.println(json.get("gender"));
}
}
```
输出结果:
```
张三
18
male
```
可以看到,我们将字符串 `jsonStr` 转换为了 JSON 对象,并且可以通过 `get` 方法获取对象中的属性值。
hutool java list 转json string
使用 Hutool 将 Java 中的 List 转换为 JSON 字符串可以使用 `cn.hutool.json.JSONUtil` 工具类,具体代码如下:
```java
List<User> userList = new ArrayList<>();
// 添加用户信息到 userList 中
String jsonStr = JSONUtil.toJsonStr(userList);
```
其中,`User` 是自定义的用户类,`toJsonStr()` 方法可以将 Java 对象转换为 JSON 字符串。
如果需要美化输出的 JSON 字符串,可以使用 `JSONUtil` 中的 `toJsonPrettyStr()` 方法,具体代码如下:
```java
String jsonStr = JSONUtil.toJsonPrettyStr(userList);
```
这样输出的 JSON 字符串会进行格式化,更加易读。
需要注意的是,在使用 Hutool 进行 JSON 转换时,需要在项目中添加 Hutool-JSON 的依赖,具体可以参考以下 Maven 依赖配置:
```xml
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-json</artifactId>
<version>x.x.x</version>
</dependency>
```
其中 `x.x.x` 是 Hutool-JSON 的版本号。