首页 \ 问答 \ 如何使用ObjectMapper Jackson反序列化泛型类型(How to deserialize a generic type with ObjectMapper Jackson)

如何使用ObjectMapper Jackson反序列化泛型类型(How to deserialize a generic type with ObjectMapper Jackson)

我正在努力尝试简化我的代码。 我有一个常见的操作,它向API发出请求并获取JSON对象。 这个json可以是CategoriesProducts等。我使用的是jackson ObjectMapper

目前我有一个方法用于每个请求,但我想在一个方法中简化它。 例如。

myMethod(String Path, Here The class Type)

其中一种常见方法是:

public List<Category> showCategories() {

    HttpClient client = HttpClientBuilder.create().build();
    HttpGet getRequest = new HttpGet(Constants.GET_CATEGORY);
    getRequest.setHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
    getRequest.setHeader(HttpHeaders.COOKIE, Login.getInstance().getToken());

    List<Category> data = null;

    HttpResponse response;
    try {
        response = client.execute(getRequest);
        data = Constants.JSON_MAPPER.readValue(response.getEntity().getContent(), new TypeReference<List<Category>>() {
        });
    } catch (IOException ex) {
        LOGGER.error("Error retrieving categories, " + ex.toString());
    }
    // TODO: Replace List<category> with Observable?
    return data;
}

在所有方法中改变的一件事是要检索的对象的类型。

可以概括该线

Constants.JSON_MAPPER.readValue(response.getEntity().getContent(), new TypeReference<List<Category>>() {
        });

成为

Constants.JSON_MAPPER.readValue(response.getEntity().getContent(), new TypeReference<List<T>>() {
        });

我试图添加为方法Class<T> class ,如此处所示,但我得到错误Cannot find symbol T


I am struggling trying to simplify my code. I have a common oppperation that makes a request to an API and gets a JSON object. This json can be Categories, Products etc. I am using jackson ObjectMapper.

Currently I have a method for each request, but I want to simplify it in one method. For example.

myMethod(String Path, Here The class Type)

One of this common methods is:

public List<Category> showCategories() {

    HttpClient client = HttpClientBuilder.create().build();
    HttpGet getRequest = new HttpGet(Constants.GET_CATEGORY);
    getRequest.setHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
    getRequest.setHeader(HttpHeaders.COOKIE, Login.getInstance().getToken());

    List<Category> data = null;

    HttpResponse response;
    try {
        response = client.execute(getRequest);
        data = Constants.JSON_MAPPER.readValue(response.getEntity().getContent(), new TypeReference<List<Category>>() {
        });
    } catch (IOException ex) {
        LOGGER.error("Error retrieving categories, " + ex.toString());
    }
    // TODO: Replace List<category> with Observable?
    return data;
}

The one thing that changes across all methods is the type of object to retrieve.

It is possible to generalize the line

Constants.JSON_MAPPER.readValue(response.getEntity().getContent(), new TypeReference<List<Category>>() {
        });

To be

Constants.JSON_MAPPER.readValue(response.getEntity().getContent(), new TypeReference<List<T>>() {
        });

I've tried to add as a param to the method Class<T> class, as shown here, but I get the error Cannot find symbol T


原文:https://stackoverflow.com/questions/28895088
更新时间:2023-10-10 18:10

最满意答案

MediaPlayerLauncher并不是真正意义上的用例。 即使在这个用例中它也能做到“好工作”。 例如,MediaPlayerLauncher不支持标题,副标题,叠加等。

如果您正在尝试播放项目列表或想要为您的媒体播放体验定制UI / UX,最好使用SmfPlayer ,而SmfPlayer又使用内置的MediaElement或SmoothStreamingMediaElement。

例如,以下是如何使用SmfPlayer for WP7创建多个项目的播放列表:

<Core:SMFPlayer>
    <Core:SMFPlayer.Playlist>
        <Media:PlaylistItem MediaSource="http://smf.vertigo.com/videos/wildlife.wmv"/>
        <Media:PlaylistItem MediaSource="http://smf.vertigo.com/videos/wildlife.wmv"/>
        <Media:PlaylistItem DeliveryMethod="AdaptiveStreaming" MediaSource="http://ecn.channel9.msdn.com/o9/content/smf/smoothcontent/bbbwp7/big buck bunny.ism/manifest"/>
    </Core:SMFPlayer.Playlist>
</Core:SMFPlayer> 

MediaPlayerLauncher isn't really meant for that usecase. And even at this usecase it does an "OK job". For example MediaPlayerLauncher doesn't support titles, subtitles, overlays, etc.

If you're trying to playback a list of items or want a tailored UI/UX for your media playback experience it's best to use SmfPlayer which in turn uses the built-in MediaElement or SmoothStreamingMediaElement.

For example, here's how to create a playlist of several items with SmfPlayer for WP7:

<Core:SMFPlayer>
    <Core:SMFPlayer.Playlist>
        <Media:PlaylistItem MediaSource="http://smf.vertigo.com/videos/wildlife.wmv"/>
        <Media:PlaylistItem MediaSource="http://smf.vertigo.com/videos/wildlife.wmv"/>
        <Media:PlaylistItem DeliveryMethod="AdaptiveStreaming" MediaSource="http://ecn.channel9.msdn.com/o9/content/smf/smoothcontent/bbbwp7/big buck bunny.ism/manifest"/>
    </Core:SMFPlayer.Playlist>
</Core:SMFPlayer> 

相关问答

更多
  • 关于如何获得高代码重用的一些想法: 目前XAML可能是您最好的语言选择...... Win8和WP8之间有很多重叠。 这里是Windows Phone 8和Windows 8之间的XAML控件比较 。 利用MVVM模式 。 这为您的UI和应用程序逻辑提供了一个很好的解耦。 使用可移植的类库 (可在Win8,WP8和其他平台上使用的DLL)。 更多信息在这里 。 或者,使用“添加为链接”引用Win8和WP8中的相同源文件。 这样,您将源代码保存在一个地方,但Win8和WP8应用程序都使用它。 使用条件编译 。 ...
  • Windows Phone 8 Silverlight是Windows Phone 8上的旧版UI。WinRT XAML用于Windows应用商店应用(这些是通用应用)。 Windows Phone 8.1 Silverlight与此处解释的有点不同。 Windows Phone尽管年龄较大,但Silverlight在某些方面更好。 如果您的目标是开发一款仅针对手机的应用程序,并且没有任何用于Win8 / RT的用途,请使用Silverlight。 背景音频在WinRT中是一团糟。 语音识别与Cortana ...
  • MediaPlayerLauncher并不是真正意义上的用例。 即使在这个用例中它也能做到“好工作”。 例如,MediaPlayerLauncher不支持标题,副标题,叠加等。 如果您正在尝试播放项目列表或想要为您的媒体播放体验定制UI / UX,最好使用SmfPlayer ,而SmfPlayer又使用内置的MediaElement或SmoothStreamingMediaElement。 例如,以下是如何使用SmfPlayer for WP7创建多个项目的播放列表: ...
  • 大部分是 - 获取当前位置(cellid,mnc,mmc,lac,lat,lng) 大部分没有 - 读/写/删除/拦截SMS,CallLog,联系人,日历,文件,笔记 否 - 获取已安装的应用程序列表 是 - 使用SQLite 否 - 电子邮件和VPN配置 MOSTLY NO - 能够启用/禁用蓝牙,GPRS,无线网络 是 - 录音 是 - 加密 大多数不 - 控制手机配置文件 是 - JSON 大多数不 - 文件系统通知 MOSTLY YES - Get current location (cellid, ...
  • 是的。 Windows Phone Silverlight 8是Windows Phone 8.1发布后给予Windows Phone 8的名称。 还有Windows Phone Silverlight 8.1和Windows Phone 8.1 。 这两者之间的区别在于Windows Phone 8.1与Windows应用商店应用兼容,而Windows Phone Silverlight 8.1不兼容。 你可以在这里了解更多关于这个: http : //msdn.microsoft.com/en-us/l ...
  • Mango确实是Windows Phone 7.5更新的代号。 Windows Phone 7.5中有许多新的API和功能,它带来了一个新的SDK(版本7.1)。 针对Windows Phone 7.0 SDK的应用在7.1下工作正常,但针对Windows Phone 7.1 SDK的应用需要运行Mango更新。 Windows Phone站点列出了Windows Phone 7.5(Mango更新)中的新功能, MSDN列出了7.0 SDK和7.1 SDK之间的API更改。 Mango was indee ...
  • 当您将应用程序提交到市场时,应用程序Guid编号将会更改,如果您在同一个应用程序中为不同的操作系统版本提交两个xaps,那么应用程序指南将是相同的。 The app Guid number will be changed when you submit the app into the market, if you submit two xaps in the same app for different OS versions the app guid will be the same.
  • 是的,Windows Phone 8.1用户可以使用Windows Phone 8.0应用程序。 因为它具有Backward compatibility 。 为Windows Phone 8目标创建的应用程序将继续在Windows Phone 8.1设备上运行,而无需重新发布。 Yes, Windows Phone 8.1 users can use Windows Phone 8.0 apps. Because it has Backward compatibility. Apps created to ...
  • 您可以在www.reddit.com/r/wp7dev/找到很多示例和参考应用程序,或者使用Twitter上的#wp7dev标签进行搜索(完全公开 - 我的一些示例出现在那里)。 有一个人们公开工作的例子,但人们可以假设它更多 - 希望这是有用的,因为它显示了可以做什么,或者正在平台上完成。 You can find a lot of examples and reference applications here www.reddit.com/r/wp7dev/ or search using the h ...
  • 根据文件: 应用程序栏包含一到四个按钮,省略号和一组文本菜单项。 有关更多信息,请参阅Windows Phone的应用栏。 看看这个链接 http://msdn.microsoft.com/en-us/library/windowsphone/develop/microsoft.phone.shell.applicationbar(v=vs.105).aspx ;) According to the documentation : An Application Bar contains between on ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)