我有以下情况:
public class A {
@JsonProperty("member")
private int Member;
}
public class B {
private int Member;
}
现在,我希望做到以下几点:
ObjectMapper mapper = new ObjectMapper();
B b = new B(); b.setMember("1");
A a = mapper.converValue(b, A.class);
通常情况下,这会奏效。但是,由于objectMapper
考虑了@JsonProperty
等注释,因此我得到以下结果:
A.getMember(); // Member = NULL
有一种解决方法,其中由于此而预期为null
的所有字段都是手动设置的,即A.setMember(b.getMember());
,但这违背了在objectMapper
中使用objectMapper
的目的。第一名并且可能容易出错。
有没有办法配置@JsonProperty
忽略给定类(或全局)的#!/bin/bash
test -r "$1" || { ## validate first argument is readable file
printf "error: file not given or not readable.\n"
exit 1
}
while read -ra line; do ## read each line into array
if test -z "$headings" ; then ## if headign not set, set it
headings=1 ## set heading used flag
printf "%s" "${line[0]}" ## print Individual
## duplicate each heading tab separated
for ((i = 1; i < ${#line[@]}; i++)); do
printf "\t%s\t%s" "${line[i]}" "${line[i]}"
done
echo "" ## tidy up with newline
elif test -z "$line1" ; then ## if line1 not set, set it
line1=( "${line[@]}" ) ## save line as line1 and get next line
else
## test that persons match
if test "${line1[0]}" = "${line[0]}" ; then
## test number of fields in each line match
if test "${#line1[@]}" != "${#line[@]}" ; then
printf "error: field mismatch - person '%s'.\n" "${line[0]}" >&2
fi
printf "%s\t" "${line[0]}" ## print the person (w/tab)
## interleave data for person from line1 line2 tab separated
for ((i = 1; i < ${#line[@]}; i++)); do
printf "\t%s\t%s" "${line1[i]}" "${line[i]}"
done
echo "" ## tidy up with newline
line1= ## unset line1 and repeat
fi
fi
done < "$1"
字段?
答案 0 :(得分:3)
您可以通过执行以下操作来配置ObjectMapper以忽略@JsonProperty之类的注释:
ObjectMapper objectMapper = new ObjectMapper().configure(
org.codehaus.jackson.map.DeserializationConfig.Feature.USE_ANNOTATIONS, false)
.configure(org.codehaus.jackson.map.SerializationConfig.Feature.USE_ANNOTATIONS, false)
但这会导致它也忽略像@JsonIgnore等等。我不知道有什么办法让ObjectMapper只忽略特定的注释。
答案 1 :(得分:0)
要忽略 all 批注,Jackson版本2.x中的语法为:
objectMapper.configure(MapperFeature.USE_ANNOTATIONS, false)
使用这种方法似乎无法忽略子集。
但是可以在以下答案中找到更好的解决方案:https://stackoverflow.com/a/55064740/3351474
您的需求应该是
public class IgnoreJacksonPropertyName extends JacksonAnnotationIntrospector {
@Override
public PropertyName findNameForSerialization(Annotated a) {
return PropertyName.USE_DEFAULT;
}
@Override
public PropertyName findNameForDeserialization(Annotated a) {
return PropertyName.USE_DEFAULT;
}
}
...
mapper.setAnnotationIntrospector(new IgnoreJacksonPropertyName());