2014-03-26 51 views
2

我創建傑克遜Pascal大小寫和@JsonProperty在吸氣

new ObjectMApper() 
     .setPropertyNamingStrategy(PropertyNamingStrategy.PASCAL_CASE_TO_CAMEL_CASE) 
     .setSerializationInclusion(Include.NON_NULL) 

一個映射,系列化完美的作品上的字段(沒有getter和setter)。字段currentStatus被序列化爲"currentStatus"(首字母大寫)。但我也有一個getter(沒有字段和setter),它必須是camelCase。所以我做:

@JsonProperty("abcDef") 
public String getZxy() {... 

,但它是序列化到"AbcDef"而不是"abcDef"。它看起來像命名策略仍然觸發並更改第一個字母。我使用jackson-databind 2.3.2;

我該如何將這個getter與第一個字母小寫映射?


編輯: 醜陋的代碼,但顯示的問題。這個測試應該通過,但它無法

import static org.assertj.core.api.Assertions.assertThat; 
import org.testng.annotations.Test; 
import com.fasterxml.jackson.annotation.JsonProperty; 
import com.fasterxml.jackson.databind.ObjectMapper; 
import com.fasterxml.jackson.databind.PropertyNamingStrategy; 

public class JsonFailureTest { 

    @Test 
    public void should_serialize_first_letter_lowercase() throws Exception { 

     String json = new ObjectMapper() 
          .setPropertyNamingStrategy(PropertyNamingStrategy.PASCAL_CASE_TO_CAMEL_CASE) 
          .writeValueAsString(

     new Object(){ 

      @JsonProperty("fooBar") 
      public String whatever() {return "";} 

     }); 

     assertThat(json).contains("fooBar"); 
    } 
} 
+0

FWIW,這是一個真正的錯誤,並報告爲https://github.com/FasterXML/jackson-databind/issues/428 – StaxMan

回答

1

下面是一個使用自定義的 「註解感知」 的策略解決方法:

import com.fasterxml.jackson.annotation.JsonInclude; 
import com.fasterxml.jackson.annotation.JsonProperty; 
import com.fasterxml.jackson.core.JsonProcessingException; 
import com.fasterxml.jackson.databind.ObjectMapper; 
import com.fasterxml.jackson.databind.PropertyNamingStrategy; 
import com.fasterxml.jackson.databind.cfg.MapperConfig; 
import com.fasterxml.jackson.databind.introspect.AnnotatedMethod; 

public class Foo { 
    public static void main(final String[] args) throws JsonProcessingException { 
     final SomeObject someObject = new SomeObject(); 
     someObject.setZxy("foobar"); 

     final ObjectMapper mapper = new ObjectMapper(); 
     mapper.setPropertyNamingStrategy(new PropertyNamingStrategy.PascalCaseStrategy() { 
      @Override 
      public String nameForGetterMethod(final MapperConfig<?> config, final AnnotatedMethod method, final String defaultName) { 
       final JsonProperty annotation = method.getAnnotation(JsonProperty.class); 
       if (annotation != null) { 
        return annotation.value(); 
       } 
       return super.nameForGetterMethod(config, method, defaultName); 
      } 
     }); 
     mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); 

     System.out.println(mapper.writeValueAsString(someObject)); 
    } 

    private static class SomeObject { 

     private String zxy; 

     @JsonProperty("abcDef") 
     public String getZxy() { 
      return this.zxy; 
     } 

     public void setZxy(final String zxy) { 
      this.zxy = zxy; 
     } 
    } 
} 

輸出:

{"abcDef":"foobar"}