Search code examples
jsonscalascalatrajson4s

Json4s producing weird Json


This is what I have:

(("foo" ->
  ("bar" -> 5) ~
  ("bar2" -> 5)) ~
 ("something" -> "else"))

This is what I get:

[
  {
   "foo": {
      "bar": 5,
      "bar2": "5"
   },
   "something": "else",
  }
]

But this is what I'd like to get back:

{
   "foo": {
      "bar": 5,
      "bar2": "5"
    },
    "something": "else",
}

What am I doing wrong here?


detail

def getAll: JValue = db withSession { implicit db: Session =>
    // getUsersQuery fetchs all users
    getUsersQuery.list.map { u =>

       ("foo" ->
       ("bar" -> 5) ~
       ("bar2" -> 5)) ~
       ("something" -> "else")

    }
}

Solution

  • You have a error in your question:

    This is what I have:

    Actually you have not a single JObject, but a collection of JObject:

    val jObject = (
      ("foo" ->
        ("bar" -> 5) ~
        ("bar2" -> 5)) ~
      ("something" -> "else")
    )
    
    val collection: JValue = List(jObject)
    

    And collection of JObject will be converted to json array (since it could be List() or List(jObject, jObject)).

    If you want to get a single value you have to extract this value from collection somehow:

    // note type inference here, it will be Seq[JObject] or similar
    def getAll = db withSession { implicit db: Session =>
        // getUsersQuery fetchs all users
        getUsersQuery.list.map { u =>
    
           ("foo" ->
           ("bar" -> 5) ~
           ("bar2" -> 5)) ~
           ("something" -> "else")
    
        }
    }
    
    for {
      j <- getAll.headOption
    } println(pretty(render(j)))
    

    For single value (like in your initial question) it works just fine:

    import org.json4s.JsonDSL._
    import org.json4s.jackson.JsonMethods._
    // or
    // import org.json4s.native.JsonMethods._
    
    val source = (
      ("foo" ->
        ("bar" -> 5) ~
        ("bar2" -> 5)) ~
      ("something" -> "else")
    )
    
    pretty(render(source))
    // String =
    // {
    //   "foo" : {
    //     "bar" : 5,
    //     "bar2" : 5
    //   },
    //   "something" : "else"
    // }
    

    Update (response to comment):

    def getAll: JValue = (1 to 2).toList map { u =>
      ("bar" -> 5) ~
      ("bar2" -> 5)
    }
    
    val result = (
      ("foos" -> getAll) ~
      ("something" -> "else")
    )
    
    pretty(render(result))
    // String =
    // {
    //   "foos":[{
    //     "bar":5,
    //     "bar2":5
    //   },{
    //     "bar":5,
    //     "bar2":5
    //   }],
    //   "something":"else"
    // }