Akka-HTTP中List[Case Class]隐式JSON Format配置报错求助
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:
- First, confirm you've imported the necessary Spray JSON classes:
import spray.json._ import DefaultJsonProtocol._
- Keep your correct format for the
Categorycase class, and delete the problematicjsCatsline:
// 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])
- 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
jsonFormatNmethods are only for case classes/products.- Standard collections get free JSON support from
DefaultJsonProtocolas long as their element type has a format in scope.
内容的提问来源于stack exchange,提问作者Dmitry Reutov

