Play framework 和 scala Convert List<T> for Json String

Play framework and scala Convert List<T> for Json String

我正在尝试将列表转换为 Json 字符串,这是我的代码

  def getProductAsJson(txt:String):String={
                var products=new ListBuffer[Product]()


                 val conn = DB.getConnection()
                 try {
                    val stmt = conn.createStatement
                    val q="SELECT * from m_products where pro_name like '"+txt+"%' "
                    println(q);
                    val rs = stmt.executeQuery(q)
                     while (rs.next()) {
                      products+=Product(Some(rs.getInt("idproduct")),rs.getString("pro_name"),rs.getBigDecimal("pro_retprice"),
                      rs.getString("pro_description"),rs.getString("pro_brand"),rs.getString("pro_type"),rs.getString("pro_sup"),rs.getString("pro_supref"),rs.getBigDecimal("pro_supprice"),rs.getBigDecimal("pro_markup"),Some(rs.getString("pro_imgpath")),rs.getInt("pro_active"));
                    }
                } finally {
                    conn.close()
                }

                println(Json.toJson(products.toList).toString)
                return Json.toJson(products.toList).toString

           } 

但我遇到了这个错误

No Json serializer found for type List[models.Product]. Try to implement an implicit Writes or Format for this type.

您是否为您的 models.Product 实施了 Writes?如果没有,请添加如下内容:

import play.api.libs.json._

implicit val productWrites = Json.writes[Product]

然后确保隐式 productWrites 在您调用 Json.toJson.

的范围内

https://www.playframework.com/documentation/2.4.x/ScalaJsonCombinators#Writes and https://www.playframework.com/documentation/2.4.x/ScalaJsonInception#writes