@JsonTypeResolver是使用多个属性进行解析的唯一选项吗? [英] Is @JsonTypeResolver the only option for resolving using multiple properties?
问题描述
我有以下格式的传入JSON数据
I have incoming JSON data in the following format
{
"header": {
"schema_id": {
"namespace": "omh",
"name": "physical-activity",
},
},
"body": {
"activity_name": "walking",
"distance": {
"value": 1.5,
"unit": "mi"
},
}
}
以及类似的Java类
public class DataPoint<T extends Measure> {
private DataPointHeader header;
private T body;
和
@JsonNaming(LowerCaseWithUnderscoresStrategy.class)
public class PhysicalActivity extends Measure {
private String activityName;
private LengthUnitValue distance;
我希望Jackson根据JSON文档中的schema_id
将body
解析为PhysicalActivity
类型,例如用伪代码
I'd like Jackson to resolve body
to the PhysicalActivity
type based on the schema_id
in the JSON document, e.g. in pseudocode
if schema_id.namespace == 'omh' && schema_id.name == 'physical-activity'
then return PhysicalActivity.class
我尝试使用@JsonTypeIdResolver
进行此操作,但是如果尝试使用@JsonTypeInfo
导航到header.schema_id.name
,例如
I've tried doing this with @JsonTypeIdResolver
but if I try to navigate to header.schema_id.name
with @JsonTypeInfo
, e.g.
@JsonTypeInfo(use = JsonTypeInfo.Id.CUSTOM,
include = JsonTypeInfo.As.EXTERNAL_PROPERTY,
property = "header.schema_id.name")
@JsonTypeIdResolver(DataPointTypeIdResolver.class)
public abstract class Measure {
我收到一个missing property: 'header.schema_id.name'
错误.即使可以,我也不认为我可以同时决定namespace
和name
属性.
I get a missing property: 'header.schema_id.name'
error. And even if I could, I don't think I can take a decision on both the namespace
and name
properties.
除了使用@JsonTypeResolver
从头开始构建之外,还有其他明智的方法吗?
Is there a sane way to do this besides building from scratch with @JsonTypeResolver
?
推荐答案
否,无法使用路径表达式来匹配属性.这将需要访问完整的JSON(子树).
No, there is no way to use path expressions for matching properties. This would require access to the full JSON (sub-tree).
对于Jackson 2.5,将类型ID设为标量值(通常是字符串)的要求稍有放松,因此可能支持JSOG .有关此问题的更多背景信息:
With Jackson 2.5, there is slight relaxation from requirement for type ids to be scalar values (usually Strings), so that JSOG may be supported. More background is on this issue:
https://github.com/FasterXML/jackson-databind/issues/622
但是我认为这还远远不足以让您使用标准的Jackson类型id解析.
But I don't think that is far enough to let you use standard Jackson type id resolution.
您可能会考虑的一件事是Creator方法,例如:
One thing you might consider are Creator methods, something like:
abstract class Measure {
// either constructor, or static method:
@JsonCreator
public static Measure construct(
@JsonProperty("header") HeadOb header, // or JsonNode, Map etc
@JsonProperty("body") JsonNode body) {
// extract type info, build actual instance from body
}
}
或Converter
,其中您使用中间包装器进行标头绑定,而主体仅绑定到JsonNode
或Map
,然后从那里构造.
or, perhaps Converter
where you use an intermediate wrapper to header bound, and body only bound to JsonNode
or Map
, and then construct from there.
这篇关于@JsonTypeResolver是使用多个属性进行解析的唯一选项吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!