2012-07-27 33 views
1

我想以這種方式序列化我的類以2種不同的方式發送一個屬性(作爲一個字符串和一個枚舉)與傑克遜序列化一個類。我如何確定傑克遜實際上將其他屬性添加到JSON輸出而不聲明它?是否可以使用Jackson的其他屬性進行序列化?

我的代碼是

private LearningForm cnfpLearningOrganisationLearningForm; 
...... 
/** 
* @return the cnfpLearningOrganisationLearningForm 
*/ 
public String getCnfpLearningOrganisationLearningFormSearch() { 
    return cnfpLearningOrganisationLearningForm.getValue(); 
} 

/** 
* @return the cnfpLearningOrganisationLearningForm 
*/ 
public LearningForm getCnfpLearningOrganisationLearningForm() { 
    return cnfpLearningOrganisationLearningForm; 
} 

我想傑克遜序列化此爲: { .... cnfpLearningOrganisationLearningForm:someValue中 cnfpLearningOrganisationLearningFormSearch:differentValue .... }

有一種沒有將cnfpLearningOrganisationLearningFormSearch聲明爲類中的(除序列化外無用的)字段的方法?

謝謝。

回答

0

@JsonProperty批註,它允許你動態評估的屬性值(你可以聲明它返回的對象,如果你想同時返回枚舉和字符串,如果我理解正確的問題)

@JsonProperty("test") 
public Object someProp(){ 
    if (condition) return SomeEnum.VALUE; 
    else 
     return "StringValue"; 
} 
+0

我沒有辦法在該位置設置條件。不過謝謝,我會和JsonProperty一起玩,看看我能做些什麼。 – Andrei 2012-07-27 13:19:16

1

如果我正確地理解了這個問題,你可以用mixins來解決這個問題。特別是因爲它聽起來像你可能無法修改實體。

0

有沒有辦法做到這一點,而不需要將cnfpLearningOrganisationLearningFormSearch聲明爲類中的(無用的,除了序列化)字段?

是的。默認情況下,Jackson將使用getters作爲屬性,而不考慮任何字段。所以,在原始問題中描述的bean應該按需要序列化,就好了。

下面的代碼演示了這一點(爲了好的度量,拋出了一個不必要的枚舉)。

import com.fasterxml.jackson.databind.ObjectMapper; 

public class JacksonFoo 
{ 
    public static void main(String[] args) throws Exception 
    { 
    System.out.println(new ObjectMapper().writeValueAsString(new Bar())); 
    // output: {"propertyAsValue":"some_value","propertyAsEnum":"VALUE"} 
    } 
} 

class Bar 
{ 
    public String getPropertyAsValue() 
    { 
    return MyEnum.VALUE.getValue(); 
    } 

    public MyEnum getPropertyAsEnum() 
    { 
    return MyEnum.VALUE; 
    } 
} 

enum MyEnum 
{ 
    VALUE; 

    public String getValue() 
    { 
    return "some_value"; 
    } 
} 
相關問題