java字符串转json
时间: 2023-07-19 10:35:47 浏览: 81
将Java字符串转换为JSON格式,可以使用Java中的JSON库,比如Jackson、Gson等。下面是使用Jackson库将Java字符串转换为JSON的示例代码:
```java
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) throws Exception {
String jsonString = "{\"name\":\"张三\",\"age\":20}";
ObjectMapper objectMapper = new ObjectMapper();
Object jsonObject = objectMapper.readValue(jsonString, Object.class);
String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
System.out.println(json);
}
}
```
这段代码将字符串`{"name":"张三","age":20}`转换为JSON格式,并输出结果:
```json
{
"name" : "张三",
"age" : 20
}
```
阅读全文