杰克逊映射器与scala中的通用类 [英] Jackson mapper with generic class in scala

查看:124
本文介绍了杰克逊映射器与scala中的通用类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试序列化 GeneralResponse

case class GeneralResponse[T](succeeded: Boolean, payload: Option[T])

且有效载荷 GroupsForUserResult

case class GroupsForUserResult(groups: Seq[UUID]).

我正在使用 mapper.readValue(response.body,classOf [GeneralResponse [ GroupsForUserResult]])但不幸的是,有效负载序列化为 Map 而不是所需的案例类( GroupForUserResult )。

I am using mapper.readValue(response.body, classOf[GeneralResponse[GroupsForUserResult]]) but unfortunately the payload is serialised as a Map and not as the desired case class (GroupForUserResult).

推荐答案

由于Java Erasure - Jackson无法在运行时知道有关通用类型T的信息该行 -

Because of Java Erasure - Jackson can't know at runtime about the generic type T from the line -

mapper.readValue(response.body, classOf[GeneralResponse[GroupsForUserResult]])

此问题的解决方案将是

import com.fasterxml.jackson.core.`type`.TypeReference

mapper.readValue(json, new TypeReference[GeneralResponse[GroupsForUserResult]] {})

这样您就可以提供 TypeReference 的实例以及所有需要的类型信息。

This way you provide an instance of TypeReference with all the needed Type information.

这篇关于杰克逊映射器与scala中的通用类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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