2012-07-27 52 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"; 
    } 
} 
相关问题