You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Akka-HTTP中List[Case Class]隐式JSON Format配置报错求助

Fixing Spray JSON Serialization for Seq[Category]

Hey there! Let's break down why those errors are popping up and get your code working smoothly.

What's Wrong With Your Current Code?

The jsonFormat1 method (and all jsonFormatN variants) are built exclusively for generating JSON formats for case classes (or other Product types). They expect a constructor that takes N parameters (hence jsonFormat1 for 1 parameter, jsonFormat3 for 3, etc.).

When you write jsonFormat1(Seq[Category]), you're passing a collection type directly to a method designed for case class constructors. That's why you're seeing those confusing type mismatch errors: the compiler can't reconcile Seq[Category] with the Product type that jsonFormat1 requires.

The Fix: Use Spray's Built-In Collection Formats

Spray JSON's DefaultJsonProtocol already provides out-of-the-box JSON formats for standard Scala collections like Seq, List, Set, etc. You don't need to manually create a format for Seq[Category]—you just need to ensure the JSON format for the individual Category elements is in scope.

Here's how to adjust your code:

  1. First, confirm you've imported the necessary Spray JSON classes:
import spray.json._
import DefaultJsonProtocol._
  1. Keep your correct format for the Category case class, and delete the problematic jsCats line:
// This is correct - jsonFormat3 matches your Category's 3 parameters
implicit val jsCat = jsonFormat3(Category)

// Remove this line entirely - it's unnecessary and causing errors!
// implicit val jsCats = jsonFormat1(Seq[Category])
  1. Now your original code will work as expected:
val res: List[Category] = CategoryObj.getCategories
complete(OK, res)

The compiler will automatically find the built-in format for List[Category] because it can use your jsCat format to serialize each individual Category in the list.

If You Want an Explicit Collection Format (Optional)

If you prefer to explicitly define the format for Seq[Category] (for clarity or custom behavior), use Spray's dedicated collection format methods instead of jsonFormatN:

implicit val jsCats: RootJsonFormat[Seq[Category]] = seqFormat[Category]
// Or use listFormat[Category] if you're working specifically with List

Recap

  • jsonFormatN methods are only for case classes/products.
  • Standard collections get free JSON support from DefaultJsonProtocol as long as their element type has a format in scope.

内容的提问来源于stack exchange,提问作者Dmitry Reutov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 10:32:27