让我先说一下我是json和序列化等的新手。我试图从一些案例类创建一些json。这是我正在玩的scala工作表中的代码:
import net.liftweb.json.DefaultFormats
import net.liftweb.json.Serialization.write
implicit val formats = DefaultFormats
// DBObjectTypes is an enumeration not shown in this snippet.
def update(dbObject: DBObjectTypes, updatePair: Map[String, Any]): Unit = {
case class Query(objectType: String, id: String, version: Long)
case class Update($set: Map[String, Any])
case class QueryUpdate(query: Query, update: Update)
val queryUpdate = QueryUpdate(Query(dbObject.toString, "test", 1L), Update(updatePair))
val updateJson = write(queryUpdate)
println(updateJson)
}
// SRAsubmission is an enumeration not show in this code snippet
update(SRAsubmission, Map("Desc" -> "Foo"))
这导致以下JSON:
{"$outer":{},"query":{"$outer":{},"objectType":"SRAsubmission","id":"test","version":1},"update":{"$outer":{},"$set":{"Desc":"Foo"}}}
我想要的内容如下:
{"query":{"objectType":"SRAsubmission","id":"test","version":1},"update":{"$set":{"Desc":"Foo"}}}
我不明白为什么我得到$ outer:{} json元素。我很确定这可能是我不理解但却无法在StackOverflow或Google上找到任何答案的基础。在此先感谢您的帮助!
答案 0 :(得分:1)
将您的案例类定义移到def之外。 外部是对它们定义的类实例的引用。
答案 1 :(得分:0)
+1克里斯托夫(Christophe)
我也遇到了这个问题,将案例类移出了逻辑类。
import ...
class clsMakeJsonFile {...}
//Case classes
case class humanBeing(height: Int, name: String, isSuperHuman: Boolean)
case class parents(names: String, nationality: String, isAlive: Boolean)
case class children(count: Int, names: String, canCode: Boolean)
答案 2 :(得分:-1)
您的案例类应该在Object和主类之间,否则您将获得外部类。您还应该从主类调用该方法。还添加了Implicit语句。请尝试这样,如果您有任何问题,请告诉我。
注意:我没有测试过这段代码。
object AdvJson {
case class Query(objectType: String, id: String, version: Long)
case class Update($set: Map[String, Any])
case class QueryUpdate(query: Query, update: Update)
def main(args: Array[String]) {
update(SRAsubmission, Map("Desc" -> "Foo"))
def update(dbObject: DBObjectTypes, updatePair: Map[String, Any]): Unit = {
implicit val format = DefaultFormats
val queryUpdate = QueryUpdate(Query(dbObject.toString, "test", 1L), Update(updatePair))
val updateJson = write(queryUpdate)
println(updateJson)
}
}
}