0

I'm trying to take the JSON output of an analysis tool, and turn it into a Java list.

I'm doing this with Scala, and while it doesn't sound that hard, I've run into trouble.

So I was hoping the following code would do it:

def returnWarnings(json: JSONObject): java.util.List[String] ={
    var bugs = new ArrayBuffer[String]
    for (warning <- json.getJSONArray("warnings").){ //might need to add .asScala
        bugs += (warning.getString("warning_type") + ": " + warning.getString("message"))
    }
    val rval: java.util.List[String] = bugs.asJava
    rval
}

This block produces two errors when I try to compile it:

Error:(18, 42) value foreach is not a member of org.json.JSONArray
        for (warning <- json.getJSONArray("warnings")){ //might need to add .asScala
                                         ^

and

Error:(21, 49) value asJava is not a member of scala.collection.mutable.ArrayBuffer[String]
        val rval: java.util.List[String] = bugs.asJava
                                                ^

I don't know what's wrong with my for loop.

EDIT: with a bit more reading, I figured out what was up with the loop. see https://stackoverflow.com/a/6376083/5843840

The second error is especially baffling, because as far as I can tell it should work. It is really similar to the code from this documentation

scala> val jul: java.util.List[Int] = ArrayBuffer(1, 2, 3).asJava
jul: java.util.List[Int] = [1, 2, 3]
Community
  • 1
  • 1
Jones
  • 1,154
  • 1
  • 10
  • 35

1 Answers1

0

You should try the following:

import scala.collection.JavaConverters._

def returnWarnings(input: JSONObject): java.util.List[String] = {
  val warningsArray = input.getJSONArray("warnings")
  val output = (0 until warningsArray.length).map { i =>
    val warning = warningsArray.getJSONObject(i)

    warning.getString("warning_type") + ": " + warning.getString("message")
  }

  output.asJava
}

That final conversion could be done implicitly (without invoking .asJava), by importing scala.collection.JavaConversions._

Paweł Jurczenko
  • 4,431
  • 2
  • 20
  • 24