Gopi Gopi - 2 months ago 9
JSON Question

Convert Set[Strings] to JSON String scala

Convert Set[Strings] to JSON String using scala programming.
Eg :

data = Set(Client_1, Client_2, Client_3)


I am trying as below,

val toString : String = new Gson().toJson(data)


which returns an empty.How to convert using scala ?

Answer

Gson is a library for Java, not for Scala, subsequently it doesn't always handle Scala collections correctly. It may indeed make sense (as others have suggested) to use a JSON framework made for Scala instead.

However you can also simply use the Java conversions to get a Java collection and pass that to your Gson instance, like this:

import collection.JavaConverters.setAsJavaSetConverter

val input: java.util.Set[String] = Set("foo", "bar", "baz").asJava
val json: String = new Gson().toJson(input) // ["foo","bar","baz"]

Or just instantiate a Java collection in the first place.

Comments