Curious Curious - 6 months ago 46
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 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 =

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

 val ints = javaList.iterator

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:


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

or same with ArrayClass

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download