写一段java代码,将对象转为字符串
时间: 2024-01-11 13:04:53 浏览: 101
可以使用Java提供的ObjectMapper类来将Java对象转换为JSON字符串。需要引入Jackson库,以下是示例代码:
```java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ObjectToString {
public static void main(String[] args) {
// 创建一个Java对象
Person person = new Person("Tom", 18);
// 创建ObjectMapper对象
ObjectMapper objectMapper = new ObjectMapper();
// 将Java对象转换为JSON字符串
try {
String jsonString = objectMapper.writeValueAsString(person);
System.out.println(jsonString);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
static class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
}
```
输出结果为:
```json
{"name":"Tom","age":18}
```
阅读全文