【发布时间】:2011-12-07 20:22:05
【问题描述】:
我正在尝试反序列化 JSON 字符串,例如(提取此位以显示问题)
{
"$type": "com.example.StringProperty",
"value": "hello world",
"name": "text",
"readOnly": false
}
进入看起来像的类层次结构
public class Property
{
public String name;
public int type;
Property(String pName, int pType) { name = pName; type = pType; }
}
public class StringProperty extends Property
{
public String value;
StringProperty(String pName, String pValue) {
super(pName, String);
value = pValue;
}
}
使用以下 mixin 注释
@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="$type")
abstract public class PropertyMixin
{
@JsonProperty
public String name;
//@JsonIgnore
//public boolean readOnly;
@JsonProperty
public int type;
PropertyMixin(@JsonProperty("name") String pName, @JsonProperty("type") int pType)
{
}
}
abstract public class StringPropertyMixin
{
@JsonProperty
public String value;
//@JsonIgnore
//public boolean readOnly;
@JsonCreator
public StringPropertyMixin(@JsonProperty("name") String pName, @JsonProperty("value") String value)
{
}
}
使用 Jackson 1.9.2,我得到的错误是
Unrecognized field "readOnly" (Class com.example.StringProperty), not marked as ignorable
我尝试使用@JsonIgnore,但这并没有帮助(检查我注释掉的代码的位置,看看我是如何尝试的)。我可能遗漏了一些东西,但我认为需要另一双眼睛来看待它并帮助我。
这是反序列化环境的样子:
objectMapper.setVisibilityChecker(objectMapper.getSerializationConfig().getDefaultVisibilityChecker()
.withFieldVisibility(JsonAutoDetect.Visibility.NONE)
.withGetterVisibility(JsonAutoDetect.Visibility.NONE)
.withSetterVisibility(JsonAutoDetect.Visibility.NONE)
.withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
MixinRegistrations module = new MixinRegistrations();
objectMapper.registerModule(module);
mixin 模块看起来像
@Override
public void setupModule(SetupContext context)
{
context.setMixInAnnotations(Property.class, PropertyMixin.class);
context.setMixInAnnotations(StringProperty.class, StringPropertyMixin.class);
}
感谢所有帮助。提前致谢。
PS:我不知道这是否会有所不同,但 JSON 是由用 .Net Framework v4 编写的库生成的。
【问题讨论】:
标签: java json jackson deserialization