【Spring Boot丨序列化、反序列化】
在Spring Boot中,对象的序列化和反序列化通常是通过使用Jackson库来实现的。Jackson是Spring Boot默认的JSON处理库。
以下是一个简单的例子,演示如何在Spring Boot应用程序中序列化和反序列化一个对象。
首先,定义一个简单的实体类:
import com.fasterxml.jackson.annotation.JsonProperty;
public class User {
@JsonProperty
private String name;
@JsonProperty
private int age;
// 构造函数、getter和setter省略
}
序列化(对象转JSON字符串):
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class SerializationExample {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
User user = new User("Alice", 30);
try {
String json = mapper.writeValueAsString(user);
System.out.println(json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}
反序列化(JSON字符串转对象):
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
public class DeserializationExample {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
String json = "{\"name\":\"Bob\",\"age\":25}";
try {
User user = mapper.readValue(json, new TypeReference<User>() {});
System.out.println(user.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
在这个例子中,我们创建了一个User
对象,并使用Jackson的ObjectMapper
将其序列化为JSON字符串。然后,我们将JSON字符串反序列化回User
对象。
注意:确保你的项目中已经包含了Jackson的依赖。如果你使用的是Spring Boot,那么通常这个依赖会自动包含在内。
评论已关闭