在 杰克逊API提供了许多方法来用JSON数据的工作。通过使用Jackson API,我们可以将Java对象转换为JSON字符串,并从JSON字符串重新构造对象。我们可以使用StdSerializer类实现自定义序列化 程序, 并且需要重写serialize(T值,JsonGenerator gen,SerializerProvider提供程序) 方法,第一个参数值 表示要序列化的值(不能为null),第二个参数gen 表示所使用的生成器输出最终的Json内容,第三个参数提供者 表示提供者,可用来获取用于序列化对象值的序列化程序。
public abstract void serialize(T value, JsonGenerator gen, SerializerProvider provider) throws IOException
import java.io.*; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.module.*; import com.fasterxml.jackson.databind.ser.std.StdSerializer; public class JacksonSerializeTest { public static void main(String[] args) throws Exception { JacksonSerializeTest test = new JacksonSerializeTest(); test.serialize(); } public void serialize() throws Exception { User user = new User(); user.setFirstName("Raja"); user.setLastName("Ramesh"); ObjectMapper mapper = new ObjectMapper(); SimpleModule module = new SimpleModule(); module.addSerializer(User.class, new UserSerializer()); mapper.registerModule(module); String jsonStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user); // pretty print System.out.println(jsonStr); } } //用户类别 class User implements Serializable { private String firstName; private String lastName; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } } //UserSerializer类 class UserSerializer extends StdSerializer<User> { public UserSerializer() { this(null); } public UserSerializer(Class<User> t) { super(t); } @Override public void serialize(User value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("firstName", value.getFirstName()); jgen.writeStringField("lastName", value.getLastName()); jgen.writeEndObject(); } }
输出结果
{ "firstName" : "Raja", "lastName" : "Ramesh" }