2015-08-26 66 views
0

我有兩個類。首先與第二課的領域。如何調用另一個自定義JsonSerializer中的JsonSerializer Jackson

class A { 
    @JsonSerializer(using = CustomBSerializer.class) 
    private B b; 
} 

class B { 
    ... 
} 

而且我有兩個自定義序列:

class CustomBSerializer extends JsonSerializer<B> { 
    ... 
} 

class CustomASerializer extends JsonSerializer<A> { 
    @Override 
    public void serialize(A a, JsonGenerator jgen, SerializerProvider provider) 
      throws IOException, JsonProcessingException { 
     jgen.writeStartObject(); 
     //write here 
     jgen.writeEndObject(); 
    } 

} 

我要補充的是什麼方法,而不是評論中CustomASerializer寫場b的序列化值與CustomBSerializer

回答

1

您可以使用writeObjectField方法。 Jackson應該使用默認或自定義序列化程序(如果存在)。

下面的例子:

import com.fasterxml.jackson.core.JsonGenerator; 
import com.fasterxml.jackson.core.JsonProcessingException; 
import com.fasterxml.jackson.databind.JsonSerializer; 
import com.fasterxml.jackson.databind.ObjectMapper; 
import com.fasterxml.jackson.databind.SerializerProvider; 
import com.fasterxml.jackson.databind.annotation.JsonSerialize; 

import java.io.IOException; 
import java.util.Date; 

public class Main { 

    public static void main(String[] args) throws Exception { 
     B b = new B(); 
     b.setProperty("Value"); 

     A a = new A(); 
     a.setB(b); 

     ObjectMapper mapper = new ObjectMapper(); 
     System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(a)); 
    } 
} 

@JsonSerialize(using = ASerializer.class) 
class A { 

    private B b; 

    public B getB() { 
     return b; 
    } 

    public void setB(B b) { 
     this.b = b; 
    } 
} 

class ASerializer extends JsonSerializer<A> { 

    @Override 
    public void serialize(A value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException { 
     gen.writeStartObject(); 
     gen.writeStringField("now", new Date().toString()); 
     gen.writeObjectField("b", value.getB()); 
     gen.writeEndObject(); 
    } 
} 

@JsonSerialize(using = BSerializer.class) 
class B { 

    private String property; 

    public String getProperty() { 
     return property; 
    } 

    public void setProperty(String property) { 
     this.property = property; 
    } 
} 

class BSerializer extends JsonSerializer<B> { 

    @Override 
    public void serialize(B value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException { 
     gen.writeStartObject(); 
     gen.writeStringField("p", value.getProperty()); 
     gen.writeEndObject(); 
    } 
} 

打印:

{ 
    "now" : "Wed Aug 26 22:27:08 CEST 2015", 
    "b" : { 
    "p" : "Value" 
    } 
} 
+0

我已經嘗試過了,但它不是用我的自定義JsonSerializer。 –

+0

你是如何爲A類註冊自定義序列化程序的? –

+0

嘗試將「JsonSerialize」註釋放在類級別上,而不是放在屬性級別上。 –

相關問題