Jackson API提供了許多方法來處理JSON資料。透過使用Jackson API,我們可以將Java物件轉換為JSON字串,並從JSON字串中重構物件。我們可以使用StdSerializer類別實作自訂序列化器,並需要重寫serialize(T value, JsonGenerator gen, SerializerProvider provider)方法,第一個參數value表示要序列化的值(不能為空),第二個參數gen表示用於輸出結果Json內容的產生器,第三個參數provider表示可用來取得用於序列化物件值的序列化器的提供者。
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); } } // User class 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 class UserSerializer extends StdSerializer<User> { public UserSerializer() { this(null); } public UserSerializer(Class<User> t) { super(t); } <strong> </strong>@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" }
以上是如何在Java中使用Jackson庫實作自訂序列化器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!