2017-03-14 59 views
1

我有一個春天啓動的項目,我有一個這樣的類:傑克遜展開/裹對象

@Value 
public class A { 
    @JsonUnwrapped 
    OrderKey key; 
    String description; 
    B b; 

    @Value 
    public static class B { 
    String description; 
    } 

} 

@Value 
public class OrderKey { 
    @JsonProperty("_key") 
    String id; 

} 

我有混入但在這個例子中爲簡潔起見添加註解。 這對於序列化爲JSON時效果很好,問題是當我試圖反序列化時,如果存在一些@JsonWrapped註釋,它可能會工作。

簡而言之,我試圖用餘下的方式使用ArangoDB,並且可以創建/讀取文檔,但我需要使用自己的值對象,但不幸的是我無法使用該密鑰作爲字符串,它被封裝爲OrderKey@Value註釋來自lombok項目。

有什麼辦法可以達到這個目的嗎?

回答

0

我最終在mixin本身內部進行了序列化/反序列化,藉此我可以避免@JsonUnwrapped註釋和密鑰的另一個mixin。

密新:

public class OrderMixin { 

    @JsonDeserialize(using = OrderKeyDeserializer.class) 
    @JsonSerialize(using = OrderKeySerializer.class) 
    @JsonProperty("_key") 
    OrderKey key; 

    @JsonProperty("description") 
    String description; 

    @JsonProperty("amount") 
    String amount; 

    @JsonProperty("operation") 
    Order.Operation operation; 

    @JsonProperty("creationDate") 
    LocalDateTime creationDate; 

    public static class OrderKeySerializer extends JsonSerializer<OrderKey> { 

     public OrderKeySerializer() { 
      super(OrderKey.class); 
     } 

     @Override 
     public void serialize(OrderKey value, JsonGenerator gen, SerializerProvider provider) throws IOException { 
      gen.writeString(value.getOrderId()); 
     } 
    } 

    public static class OrderKeyDeserializer extends JsonDeserializer<OrderKey> { 

     public OrderKeyDeserializer() { 
      super(OrderKey.class); 
     } 

     @Override 
     public OrderKey deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException { 
      JsonNode node = jsonParser.getCodec().readTree(jsonParser); 

      return OrderKey.get(node.asText()); 
     } 
    } 

} 

值對象:

@Value 
public class Order implements Serializable { 

    private static final long serialVersionUID = 901109456762331944L; 

    OrderKey key; 

    String description; 

    String amount; 

    Operation operation; 

    LocalDateTime creationDate; 

    @Value 
    public static class Operation { 

    String id; 

    String description; 

    String status; 

    LocalDateTime creationDate; 
    } 

} 


@Value 
public class OrderKey implements Serializable { 

    private static final long serialVersionUID = -8102116676316181864L; 

    private String orderId; 

    public static OrderKey get(String orderId) { 
     return new OrderKey(orderId); 
    } 

} 
0

您可以嘗試在class A中定義一個構造函數,並使用@JsonCreator註釋。然後Jackson可以使用此構造函數創建一個A對象,並將您期望的JSON文檔中的字段映射到A的字段。簡單的例子:

@Value 
public class A { 
    @JsonUnwrapped 
    OrderKey key; 
    String description; 

    @JsonCreator 
    public A(@JsonProperty("key") String key, 
      @JsonProperty("description") String description) { 
     this.key = new OrderKey(key); 
     this.description = description; 
    } 
} 

注意,此構造爲A將阻止@AllArgsConstructor構造函數通過@Value暗示的創建。

也可以避免使用Java 8和一些額外模塊的構造函數註釋。請檢查我的其他答案this