简体   繁体   English

Jackson 从对象列表中过滤和反序列化

[英]Jackson Filter and Deserialize from a List of Objects

Consider I have a DTO class like below:考虑我有一个如下所示的 DTO 类:

    class MyDTO {
        Type property1;
        Type property2;
        // ... and so on
    }

Now I have an API that returns a list of MyDTO objects.现在我有一个返回MyDTO对象列表的 API。 But I want to filter out and get the single object MyDTO from this list of objects based on some criteria (say property1 == some value).但是我想根据某些条件(比如 property1 == 某个值)从这个对象列表中过滤并获取单个对象MyDTO

I know , I can do this by using streams after getting the list of objects.我知道,我可以在获取对象列表后使用streams来做到这一点。 But is there any Jackson way of doing it?但是有没有杰克逊的方法呢? so that in my Feign Client call I can have single object as a return type.这样在我的Feign Client调用中,我可以将单个对象作为返回类型。

    // returns a single object after filtering 
    // for one object while serializing.
    MyDTO feignCallApi() 

No. Jackson is only used for serializing/deserializing data.不,Jackson 仅用于序列化/反序列化数据。 In your scenario described, the below are 2 possibilities:在您描述的场景中,以下是两种可能性:

Option 1 - API provides filtering capabilities with eg query params选项 1 - API 提供过滤功能,例如查询参数

The API you communicate with provides a possibility to filter out the desired object using some query param.您与之通信的 API 提供了使用某些查询参数过滤掉所需对象的可能性。

Option 2 - introduce intermediary layer in your application选项 2 - 在您的应用程序中引入中间层

Introduce an intermediary layer, eg a service class that utilizes the client, and performs any necessary filtering on the result of the call using eg a stream.引入中间层,例如利用客户端的服务类,并使用例如流对调用结果执行任何必要的过滤。

Calling class -> service class -> fiegn client

Then the service class can still have a method that returns only 1 MyDTO object.那么服务类仍然可以有一个只返回 1 个 MyDTO 对象的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM