杰克逊帕斯卡尔案和@JsonProperty在吸气器上

时间:2014-03-26 16:55:58

标签: java json jackson

我用

创建一个mapper
new ObjectMApper()
        .setPropertyNamingStrategy(PropertyNamingStrategy.PASCAL_CASE_TO_CAMEL_CASE)
        .setSerializationInclusion(Include.NON_NULL)

和序列化在字段上完美运行(没有getter和setter)。字段currentStatus序列化为"currentStatus"(首字母大写)。但我还有一个必须是camelCase的getter(没有字段和setter)。所以我这样做:

@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");
    }
}

1 个答案:

答案 0 :(得分: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"}