Jersey 解析 JSON/Jackson 子类型反序列化的规则 [英] Rules for Jersey to parse JSON/ Jackson Subtype deserialisation

查看:23
本文介绍了Jersey 解析 JSON/Jackson 子类型反序列化的规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以这种方式接收 JSON:

I receive JSONs the way:

@POST
@Path("log")
public Map<String, List<OperationResult>> log(Stats stats) {
  ..
}

JSON 示例:

{
  "eventType": 1
  "params": {
    "field1" : 10
  }
}

{
  "eventType": 2
  "params": {
    "field2" : "ten"
  }
}

我有一个类结构(它们是由jsonschema2pojo生成的,假设没关系):

I have a class structure (they are generated by jsonschema2pojo, suppose it does not matter):

interface Params;
class Params1 implements Params{ public int field1; }
class Params2 implements Params{ public String field2; }

class Stats {
  public int eventType;
  public Params params;
}

如何让 Jersey 解析 JSON,以便如果 eventType = 1 则 stats.params 成为 Params1 的实例,否则成为 Params2 的实例?

How can I make Jersey to parse JSONs so that if eventType = 1 then stats.params becomes an instance of Params1 and else of Params2?

推荐答案

今天早上我花了一些时间来解决这个问题.一个有趣的用例.我想出了如何做到这一点,但我不得不稍微改变你的 json.这不是绝对必要的,但是类型转换不是您的问题的一部分,因此我们可以根据需要进行跟进:)

I spent some time to work this out this morning. An interesting usecase. I figured out how to do that, but I had to change your json slightly. This is not strictly necessary, however type-conversion wasn't partof your question, so we can do a follow up if needed :)

你的json:

artur@pandaadb:~/tmp/test$ cat 1.json 
{
  "eventType": "1",
  "params": {
    "field1" : 10
  }
}
artur@pandaadb:~/tmp/test$ cat 2.json 
{
  "eventType": "2",
  "params": {
    "field2" : "10"
  }
}

我正在使用这 2 个文件来执行请求.请注意,我将 eventType 更改为字符串而不是数字.我稍后会指出这一点.

I am using those 2 files to do the request. Note that I changed the eventType t be a String rather than a number. I will point that out later.

你的模型对象:

public class Stats {

    @JsonProperty
    int eventType;


    public Params params;

    @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.EXTERNAL_PROPERTY, property="eventType")
    @JsonSubTypes({ @Type(value = Param1.class, name = "1"), @Type(value = Param2.class, name = "2") })
    public void setParams(Params params) {
        this.params = params;
    }
}

我正在使用 JsonTypeInfo,这就是它的作用:

I am using JsonTypeInfo, here's what this does:

JsonTypeInfo.Id.NAME 

逻辑类型名称,在你的例子中是属性eventType"

logical type name, in your case it is the property "eventType"

JsonTypeInfo.As.EXTERNAL_PROPERTY 

表示外部属性用于反序列化上下文.您只能在属性上使用它,而不是作为 Params 本身的类注释.这就是我注释setter方法而不是接口类的原因.

Means that an external property is used for deserialisation context. You can only use that on the property, not as a class annotation on Params itself. That is why I annotate the setter method instead of the interface class.

property="eventType" 

简单地告诉杰克逊使用什么属性名

Simply tells jackson what property name to use

然后在 JsonSubTypes 我注释了可能的选项,在你的情况下 2:

Then in the JsonSubTypes I annotate the options that are possible, in your case 2:

@Type(value = Param1.class, name = "1") 

这告诉杰克逊在 eventType 属性为1"的情况下使用 Param1.class

this tells jackson to use Param1.class in case the eventType property is "1"

PAram2.class 也一样,属性值为2"

Accordingly the same for PAram2.class and the property value being "2"

注意这就是为什么我稍微改变了 json.子类型注释不能将整数作为属性.现在您可以使用不同的选项,例如在运行时将整数属性转换为字符串的 TypeConverters,这样您就可以保持 json 相同.我跳过了这一步,但是一个快速的谷歌会给你如何做到这一点的说明.

NOTE This is why I changed the json slightly. The subtype annotations can not take an integer as property. Now there are different options you could be using, e.g. TypeConverters that convert your integer property into a string at runtime, and that way you can keep your json the same. I skipped that step, a quick google will give you instructions on how to do that though.

现在你的参数模型看起来像这样:

Now your parameter model looks like that:

public interface Params {

    public static class Param1 implements Params {
        @JsonProperty
        int field1;
    }

    public static class Param2 implements Params {

        @JsonProperty
        String field2;
    }

}

我正在对属性进行注释,以便杰克逊知道要反序列化这些属性.

I am annotating the properties so Jackson knows to deserialise those.

注意我遇到了一点问题,因为有两个属性在我懒惰疲惫的眼睛看来是一样的:

NOTE I had a bit of an issue because there are two properties that to my lazy tired eyes look the same:

JsonTypeInfo.As.EXTERNAL_PROPERTY
JsonTypeInfo.As.EXISTING_PROPERTY

您不能使用 EXISTING :D 这实际上需要十分钟才能弄清楚.有趣的事实是,我在上面写了两行,并一直在评论其中的一个,但不明白为什么其中一条抛出异常,而另一条则有效.

You can not use EXISTING :D This literally took ten minutes to figure out. Fun fact, I had both lines above and kept commenting one out, not getting why on earth one of them is throwing an exception while the other works.

无论如何.

最后是测试:

artur@pandaadb:~/tmp/test$ curl -XPOST  "localhost:8085/api/v2/test" -d @1.json -H "Accept: application/json" -H "Content-Type: application/json"
io.gomedia.resource.Params$Param1
artur@pandaadb:~/tmp/test$ 
artur@pandaadb:~/tmp/test$ curl -XPOST  "localhost:8085/api/v2/test" -d @2.json -H "Accept: application/json" -H "Content-Type: application/json"
io.gomedia.resource.Params$Param2

请注意,资源正在打印实例化类的名称.如您所见,两个 json 都已反序列化为正确的实例类.

Note that the resource is printing the name of the instantiated class. As you can see both json have been deserialised into the correct instance class.

希望对你有帮助:)

阿图尔

(有趣的事实 #2:在我的回答中,我还使用了 EXISTING 而不是 EXTERNAL,只是没有看到它.为了我的理智,我可能需要让 jackson 更改他们的名字)

(Fun fact #2: In my answer I also used EXISTING and not EXTERNAL and just didn't see it. I might need to ask jackson to change their names for my sanity's sake)

编辑

我刚试过,Jackson 很聪明,可以为你转换 json.因此,您可以将 json 保留原样,只需将模型中的属性作为字符串(如所示).一切正常.

I just tried it, and Jackson is smart enough to convert your json for you. So, you can leave the json as is, and simply have the property in your model as a String (as demonstrated). Everything works fine.

不过,为了完整起见,如果您需要一个转换器(因为您可能需要它来将您的字符串模型转换回整数以进行序列化),这将是一个整数到字符串的转换器:

For completeness though, in case you want a converter (because you might need that to convert your string model back into an integer for serailisation), this would be a integer-to-string converter:

public class EventTypeConverter implements Converter<Integer, String>{

    @Override
    public String convert(Integer value) {
        return String.valueOf(value);
    }

    @Override
    public JavaType getInputType(TypeFactory typeFactory) {
        return SimpleType.construct(Integer.class);
    }

    @Override
    public JavaType getOutputType(TypeFactory typeFactory) {
        return SimpleType.construct(String.class);
    }

}

您可以通过以下方式使用它:

You can use it by doing:

@JsonProperty
@JsonDeserialize(converter=EventTypeConverter.class)
String eventType;

这篇关于Jersey 解析 JSON/Jackson 子类型反序列化的规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆