Curious Curious - 1 month ago 6
Scala Question

scala gson array elements to scala ArrayList[Int]

I'm facing problem converting back and forth between java, gson, scala. How should i do that.

How should i do in functional way my objective is to collect all the array elements for jsonArray and populate it to the ArrayClass array.

import java.lang.reflect.Type
import java.util.ArrayList

import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import scala.collection.JavaConversions._

class ArrayClass {
var array = new ArrayList[Int]
}

class ArrayClassDeserializer extends JsonDeserializer[ArrayClass] {

def deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): ArrayClass = {
val jsonObject = json.getAsJsonObject
val jsonArray = jsonObject.get("array").getAsJsonArray
val arrayClass = new ArrayClass
val arraylist = new ArrayList[JsonElement]()
**jsonArray.iterator().foreach(e => arrayClass.array.add(e.getAsInt))**
}

Answer Source

You don't need for vague construction with ArrayClass and nested field array you can make direct transformation with converted type and map function:

import scala.collection.JavaConversions._

val javaList = new java.util.ArrayList[Int]()
val result = javaList.iterator.toList.map(_.getAsInt)

If you don't need for ArrayList as temporary result holder, just cast it to the correct type:

 val ints = javaList.iterator
                      .asInstanceOf[java.util.Iterator[Int]]
                      .toList.map(_.getAsInt)

If you don't want to deal with Scala's collections just make an iterator which returns getAsInt and convert it to ArrayList via Guava:

import com.google.common.collect.Lists;

Iterator<Integer> ints = ....
List<Integer> myList = Lists.newArrayList(ints);

or same with ArrayClass

Iterator<ArrayClass> ints = ....
List<Integer> myList = Lists.newArrayList(ints).stream.map(p -> p.getAsInt).collect(Collectors.toList());

In result, you will obtain List of Integers, the choice is yours.