You need to enable JavaScript to run this app. 如何将类作为参数传入jsoniter-scala的JsonCodecMaker实现通用JSON解析?
优惠活动
大模型
产品
解决方案
定价
更多

如何将类作为参数传入jsoniter-scala的JsonCodecMaker实现通用JSON解析?

核心问题根源

之前所有尝试失效的本质原因有两点:

  • Scala存在泛型运行时擦除机制,运行时拿到的类引用无法携带编译期需要的完整类型结构
  • jsoniter-scala的JsonCodecMaker.make完全依赖编译期Scala宏完成代码生成,必须在编译阶段就明确目标类型,无法通过运行时反射临时生成编解码器

之前尝试的公共特质方案失效的原因:如果将泛型的类型约束收敛到公共特质上,编译期拿到的是特质本身的类型,而非具体的样例子类型,宏会为特质类型生成编解码器,无法匹配到具体样例类的字段结构。

可行实现方案

最简通用泛型实现

不需要额外传递类引用,完全依赖Scala的编译期类型推断即可完成逻辑,代码示例:

import com.github.plokhotnyuk.jsoniter_scala.core._
import com.github.plokhotnyuk.jsoniter_scala.macros._

def parseJson[T](jsonString: String): T = {
  // 宏在编译期捕获T的类型,自动生成对应编解码器
  implicit val codec: JsonValueCodec[T] = JsonCodecMaker.make[T]
  readFromString[T](jsonString)
}

调用方式(编译器自动从返回值类型推断T的具体值):

val result1: JsonTypeOne = parseJson(json1String)
val result2: JsonTypeTwo: = parseJson(json2String)

这种方式是性能最高、代码最少的实现,没有运行时额外开销。

适配预期传参形式的实现

如果想要完全匹配预期的、将样例类伴生对象作为第一个参数传入的调用形式,可以通过类型类做类型关联实现:

  1. 定义辅助类型类,建立伴生对象和对应样例类的类型关联:
    trait CompanionAssoc[T] {
      type Target
    }
    
    // 为每个样例类的伴生对象定义关联实例
    given CompanionAssoc[JsonTypeOne.type] {
      type Target = JsonTypeOne
    }
    given CompanionAssoc[JsonTypeTwo.type] {
      type Target = JsonTypeTwo
    }
    
  2. 定义通用解析函数,隐式解析关联的目标类型:
    def getJsonWithClass[T](companion: T, jsonString: String)(using assoc: CompanionAssoc[T]): assoc.Target = {
      implicit val codec: JsonValueCodec[assoc.Target] = JsonCodecMaker.make[assoc.Target]
      readFromString[assoc.Target](jsonString)
    }
    

调用方式完全匹配预期:

val result1 = getJsonWithClass(JsonTypeOne, json1String)
val result2 = getJsonWithClass(JsonTypeTwo, json2String)

基于Class对象的实现

如果希望通过传递运行时Class对象的形式触发解析,也可以通过泛型推断实现:

def getJsonWithClass[T](targetClass: Class[T], jsonString: String): T = {
  implicit val codec: JsonValueCodec[T] = JsonCodecMaker.make[T]
  readFromString[T](jsonString)
}

调用方式:

val result1 = getJsonWithClass(classOf[JsonTypeOne], json1String)
val result2 = getJsonWithClass(classOf[JsonTypeTwo], json2String)

这种方式本质上还是通过泛型参数T携带编译期类型信息,运行时的Class对象仅做标记作用,不会参与编解码器的生成逻辑。

常见避坑点
  • 不要尝试将运行时获取的Class实例直接传入JsonCodecMaker.make方法,宏在编译阶段无法读取运行时的值,会直接报编译错误
  • 不要将公共特质作为泛型的唯一类型约束,否则宏生成的编解码器无法识别具体子类型的字段结构
  • jsoniter-scala的所有编解码器生成逻辑都是编译期完成的,不存在运行时动态生成编解码器的API路径,所有实现必须围绕编译期类型传递的逻辑设计

内容的提问来源于stack exchange,提问作者Peter K.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.23 12:15:08