jijesh Aj
jijesh Aj

Reputation: 614

Convert scala list to json using loop

I tried a lot to convert my scala list to Json using while loop; the code is as follows:

 var json = null
 while (list != null) {
   json = new Gson().toJson(list)
 }

the json variable must be accessed outside of the loop, so I declared it outside of the loop and initialized with null, but the Scala compiler gives me a type mismatch exception...

Upvotes: 0

Views: 667

Answers (2)

tuxdna
tuxdna

Reputation: 8487

This function works fine for List and Map both using plain Scala constructs:

def toJson(a: Any): String = {
  a match {
    // number
    case m: Number => m.toString
    // string
    case m: String => "\"" + m + "\""
    case m: Map[AnyRef, AnyRef] => {
"{" + (m map { x => val key = x._1; toJson(key) + ": " + toJson(m(key)) } mkString (", ")) + "}"
}

    case l: Seq[AnyRef] => { "[" + (l map (toJson(_)) mkString (",")) + "]" }

    // for anything else: tuple
    case m: Product => toJson(m.productIterator.toList)
    case m: AnyRef => "\"" + m.toString + "\""
  }
}

Complete example is located here: https://gist.github.com/tuxdna/7926531

Upvotes: 0

Erik Kaplun
Erik Kaplun

Reputation: 38247

Why are you using a while loop to convert a single list to JSON? Until you explain why you need a loop (or, repeated conversions to JSON, more generally speaking), I'd suggest the following trivial snippet:

val json = new Gson().toJson(list)

Note that I've also changed var json to val json.

However, if all you want to know is how to get rid of the type mismatch exception, just change:

var json = null

to

var json: String = null

or

var json: String = _

If you don't declare json to be of type String, Scala will implicitly take it to be (i.e. infer) of type Null, and it's not possible to assign values of type String to a variable of type Null.

Upvotes: 3

Related Questions