2016-11-17 60 views
1

我有一個問題。我只是使用傑克遜json的反序列化構建器模式的例子,但我總是得到一個空的json。 我使用jackson-databind版本2.8.4 我錯過了什麼嗎? 所以我的代碼如下:建設者模式json反序列化

價值類

import com.fasterxml.jackson.databind.annotation.JsonDeserialize; 

@JsonDeserialize(builder=ValueBuilder.class) 
public class Value { 
    private final int x, y; 
    protected Value(int x, int y) { 
     this.x = x; 
     this.y = y; 
    } 
} 

的ValueBuilder類

import com.fasterxml.jackson.annotation.JsonCreator; 

//@JsonPOJOBuilder(buildMethodName = "build", withPrefix = "with") 
public class ValueBuilder { 
    private int x; 
    private int y; 

    // can use @JsonCreator to use non-default ctor, inject values etc 
    public ValueBuilder() { } 

    // if name is "withXxx", works as is: otherwise use @JsonProperty("x") or @JsonSetter("x")! 
public ValueBuilder withX(int x) { 
    this.x = x; 
    return this; // or, construct new instance, return that 
} 
public ValueBuilder withY(int y) { 
    this.y = y; 
    return this; 
} 
@JsonCreator 
public Value build() { 
    return new Value(x, y); 
    } 
} 

Start類

public class Start { 
    public static void main(String[] args) throws IOException { 
     Value newValue = new ValueBuilder().withX(2).withY(4).build(); 
     ObjectMapper mapper = new ObjectMapper(); 
     String jsonString = mapper.writeValueAsString(newValue); 
     System.out.println(jsonString); 
    } 
} 
+0

不知道爲什麼這是downvoted ... – Mena

+0

反序列化器將用於.readValue *你打電話.writeValue *這將需要一個串行器。 – NateN

回答

0

你只是缺少干將訪問xy在您的Value類 - ObjectMapper需要訪問那些才能序列化。

以下內容添加到您的Value類定義:

public int getX() { 
    return x; 
} 
public int getY() { 
    return y; 
} 

無需在這方面的額外的註解。

你的JSON會打印出像:

{"x":2,"y":4} 

你也可以使這些字段public達到相同的結果,但這樣會玷污適當的封裝。

+0

但是構建器模式的方法是不在值類中設置setter,不是嗎?因此,從2.x版本開始,jackson lib支持帶有註釋「@JsonDeserialize(builder = ValueBuilder.class)」的構建器模式,或者如果我在構建器類中使用了不同的「setter」 「我需要用」@JsonPOJOBuilder(buildMethodName =「build」,withPrefix =「set」)「來註釋構建器。 – MultiShinigami30

+0

它現在有效。這兩種方式,以序列化和反序列化。我像你所說的那樣在Value類中添加了getters,並在構建器類中做了一些註釋。我的用例是有一些屬性,它們是可選的,比如x總是需要的,y是可選的。因此我添加了:private @JsonProperty(「y」)int y;並在構建器的構造函數中:public ValueBuilder(@JsonProperty(「x」)int x){this.x = x; }還爲x刪除了構建器setter方法,因爲在創建和conf時總是需要x。對於ObjectMapper:mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false); – MultiShinigami30