Created
October 19, 2017 23:03
-
-
Save brianyu0717/3a2a6723c268d38239e9db7a9a8520a3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.lang.reflect.Type | |
| import java.util | |
| import com.google.gson._ | |
| /** | |
| * Cannot get scala list to work nicely so resorted to Java List for the time being | |
| */ | |
| object SimpleExample extends App { | |
| lazy val gson: Gson = new GsonBuilder() | |
| .registerTypeHierarchyAdapter(classOf[Seq[Any]], new ListSerializer) | |
| .setPrettyPrinting() | |
| .create() | |
| class ListSerializer extends JsonSerializer[Seq[Any]] {//with JsonDeserializer[Seq[Any]] { | |
| override def serialize(src: Seq[Any], typeOfSrc: Type, context: JsonSerializationContext): JsonElement = { | |
| import scala.collection.JavaConverters._ | |
| context.serialize(src.toList.asJava) | |
| } | |
| // override def deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Seq[Any] = { | |
| // if (json.isJsonArray) { | |
| // val array: JsonArray = json.getAsJsonArray | |
| // (for (i <- 0 until array.size()) yield context.deserialize(array.get(i).getAsJsonObject, typeOfT)).toList | |
| // } else { | |
| // context.deserialize(json.getAsJsonObject, typeOfT) | |
| // } | |
| // } | |
| } | |
| case class User(name: String, age: Int, friends: util.List[User]) | |
| val friends : util.List[User] = new util.ArrayList | |
| friends.add(User("Dan", 5, new util.ArrayList)) | |
| friends.add(User("Janis", 7, new util.ArrayList)) | |
| val user: User = User("Jane", 12, friends) | |
| // val user: User = User("Jane", 12, List(User("Dan", 5, Nil), ArrayList("Janis", 7, Nil))) | |
| println(gson.toJson(user)) | |
| println(gson.fromJson( | |
| """ | |
| |{ | |
| | "name": "john", | |
| | "age": 55, | |
| | "friends": [ | |
| | { | |
| | "name": "Gina", | |
| | "age": 89, | |
| | "friends": [] | |
| | } | |
| | ] | |
| |} | |
| """.stripMargin, classOf[User])) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment