java中String转json
时间: 2023-03-03 17:39:29 浏览: 120
将Java中的String类型转换为JSON格式,通常需要使用JSON库来进行转换。常见的JSON库有Jackson、Gson、FastJSON等。
以下是使用Jackson库将String转换为JSON格式的示例代码:
```java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
public class StringToJsonExample {
public static void main(String[] args) {
String jsonString = "{\"name\":\"张三\",\"age\":20}";
ObjectMapper objectMapper = new ObjectMapper();
try {
// 将字符串转换为JSON对象
Object json = objectMapper.readValue(jsonString, Object.class);
// 将JSON对象转换为字符串
String jsonStr = objectMapper.writeValueAsString(json);
System.out.println(jsonStr);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}
```
在以上示例中,我们首先定义了一个包含姓名和年龄的JSON格式的字符串。然后使用Jackson库的ObjectMapper类将该字符串转换为JSON对象,再将JSON对象转换为字符串并打印输出。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)