问题
Let me preface by saying I am new to working with json and serialization and such. I am trying to create some json from some case classes. Here is my code from a scala worksheet I'm playing with:
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"))
This results in the following JSON:
{"$outer":{},"query":{"$outer":{},"objectType":"SRAsubmission","id":"test","version":1},"update":{"$outer":{},"$set":{"Desc":"Foo"}}}
What I want is as follows:
{"query":{"objectType":"SRAsubmission","id":"test","version":1},"update":{"$set":{"Desc":"Foo"}}}
I don't understand why I get the $outer: {} json elements. I'm pretty sure this is probably something fundamental that I don't understand but was not able to find any answers on StackOverflow or Google. Thanks in advance for any help!
回答1:
Move your case class definitions outside of the def. The outer is a reference to the instance of the class they re defined in.
回答2:
+1 Christophe
I also had this issue, moving my case classes out of my logic class worked.
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)
回答3:
Your case class should be between Object and the main class otherwise you would get the outer. Also you should call the method from main class. Added Implicit statement as well. Try like this and let me know if you have any issues.
Note: I have not tested this code.
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)
}
}
}
来源:https://stackoverflow.com/questions/42585616/why-do-i-get-outer-in-my-json-string-when-using-lift-json