Scala JSON

I wanted to have a way to automatically de/serialize scala classes to/from JSON.  The only library that does it rather effortlessly is Play JSON; as described here.

 

As suggested, the best way is to use the companion object.

WARNING:
you should define it in a separate file; otherwise you might run into context issues.
you should import this file explicitly (in the class where you are using it): import Label._

Here is the contents of Person.scala

import play.api.libs.json.Json

case class Person(name: String, age: Int)

object Person{
  implicit val personFmt = Json.format[Person]
  implicit val personWrites = Json.writes[Person]
  implicit val personReads = Json.reads[Person]
}

 

The you can easily de/serialize JSON:

import play.api.libs.json.Json
import Person._ // make sure to import your companion object

// YOUR CLASS ...

  // serialize to json
  val json = Json.toJson(Person("test", 30))
  // deserialize
  var person = json.as[Person]

ps in this case `json` is jsvalue; if you are dealing with string you’ll need to do that conversion first; e.g.:

Json.parse(strPerson).as[Person]

Notes

Scala Version

Make sure that you scala version in your build.sbt; e.g.:

scalaVersion := "2.11.8"

matches with the scala version specified for play-json

libraryDependencies += "com.typesafe.play" % "play-json_2.11" % "2.4.0-M2"

I spent half an hour solving cryptic error (before realizing that I was using scala 2.12)

[error] (run-main-0) java.lang.NoClassDefFoundError: scala/Product$class
java.lang.NoClassDefFoundError: scala/Product$class

Java Time

There was a version conflict with java time;  the version that worked was:

libraryDependencies += "com.typesafe.play" % "play-json_2.11" % "2.4.0-M2"

p.s. Tried up to 2.4.0-RC1

 

 

The following might happen if you don’t quite follow the instructions

Problem

[error] missing or invalid dependency detected while loading class file ‘DefaultWrites.class’.
[error] Could not access type Instant in value java.time,
[error] because it (or its dependencies) are missing. Check your build definition for
[error] missing or conflicting dependencies. (Re-run with `-Ylog-classpath` to see the problematic classpath.)
[error] A full rebuild may help if ‘DefaultWrites.class’ was compiled against an incompatible version of java.time.
[error] missing or invalid dependency detected while loading class file ‘DefaultWrites.class’.
[error] Could not access type LocalDate in value java.time,
[error] because it (or its dependencies) are missing. Check your build definition for
[error] missing or conflicting dependencies. (Re-run with `-Ylog-classpath` to see the problematic classpath.)
[error] A full rebuild may help if ‘DefaultWrites.class’ was compiled against an incompatible version of java.time.
[error] missing or invalid dependency detected while loading class file ‘DefaultWrites.class’.
[error] Could not access type ZonedDateTime in value java.time,
[error] because it (or its dependencies) are missing. Check your build definition for
[error] missing or conflicting dependencies. (Re-run with `-Ylog-classpath` to see the problematic classpath.)
[error] A full rebuild may help if ‘DefaultWrites.class’ was compiled against an incompatible version of java.time.
[error] missing or invalid dependency detected while loading class file ‘DefaultWrites.class’.
[error] Could not access type LocalDateTime in value java.time,
[error] because it (or its dependencies) are missing. Check your build definition for
[error] missing or conflicting dependencies. (Re-run with `-Ylog-classpath` to see the problematic classpath.)
[error] A full rebuild may help if ‘DefaultWrites.class’ was compiled against an incompatible version of java.time.
[error] missing or invalid dependency detected while loading class file ‘DefaultReads.class’.
[error] Could not access type Instant in value java.time,
[error] because it (or its dependencies) are missing. Check your build definition for
[error] missing or conflicting dependencies. (Re-run with `-Ylog-classpath` to see the problematic classpath.)
[error] A full rebuild may help if ‘DefaultReads.class’ was compiled against an incompatible version of java.time.
[error] missing or invalid dependency detected while loading class file ‘DefaultReads.class’.
[error] Could not access type LocalDate in value java.time,
[error] because it (or its dependencies) are missing. Check your build definition for
[error] missing or conflicting dependencies. (Re-run with `-Ylog-classpath` to see the problematic classpath.)
[error] A full rebuild may help if ‘DefaultReads.class’ was compiled against an incompatible version of java.time.
[error] missing or invalid dependency detected while loading class file ‘DefaultReads.class’.
[error] Could not access type ZonedDateTime in value java.time,
[error] because it (or its dependencies) are missing. Check your build definition for
[error] missing or conflicting dependencies. (Re-run with `-Ylog-classpath` to see the problematic classpath.)
[error] A full rebuild may help if ‘DefaultReads.class’ was compiled against an incompatible version of java.time.
[error] missing or invalid dependency detected while loading class file ‘DefaultReads.class’.
[error] Could not access type LocalDateTime in value java.time,
[error] because it (or its dependencies) are missing. Check your build definition for
[error] missing or conflicting dependencies. (Re-run with `-Ylog-classpath` to see the problematic classpath.)
[error] A full rebuild may help if ‘DefaultReads.class’ was compiled against an incompatible version of java.time.
[error] 8 errors found
[error] (compile:compileIncremental) Compilation failed

 

Other Error

No Json serializer found for type Try to implement an implicit Writes or Format for this type.
[error] println(“json: ” + Json.toJson(lbl))
[error] ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed

 

Other Error

You’ll get this error if your play-json’s scala version doesnt match the scala version you are using:

[error] (run-main-0) java.lang.NoClassDefFoundError: scala/Product$class
java.lang.NoClassDefFoundError: scala/Product$class
at play.api.libs.json.jackson.ReadingMap.<init>(JacksonJson.scala:108)
at play.api.libs.json.jackson.JsValueDeserializer.deserialize(JacksonJson.scala:153)
at play.api.libs.json.jackson.JsValueDeserializer.deserialize(JacksonJson.scala:120)
at play.api.libs.json.jackson.JsValueDeserializer.deserialize(JacksonJson.scala:115)
at com.fasterxml.jackson.databind.ObjectMapper._readValue(ObjectMapper.java:3779)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2050)
at play.api.libs.json.jackson.JacksonJson$.parseJsValue(JacksonJson.scala:238)
at play.api.libs.json.Json$.parse(Json.scala:21)
at org.activeintel.patentbot.server.Driver$.$anonfun$new$1(Driver.scala:35)
at org.activeintel.patentbot.server.Driver$.$anonfun$new$1$adapted(Driver.scala:28)
at scala.collection.Iterator.foreach(Iterator.scala:929)
at scala.collection.Iterator.foreach$(Iterator.scala:929)
at scala.collection.AbstractIterator.foreach(Iterator.scala:1406)
at scala.collection.IterableLike.foreach(IterableLike.scala:71)
at scala.collection.IterableLike.foreach$(IterableLike.scala:70)
at scala.collection.AbstractIterable.foreach(Iterable.scala:54)
at org.activeintel.patentbot.server.Driver$.delayedEndpoint$org$activeintel$patentbot$server$Driver$1(Driver.scala:28)
at org.activeintel.patentbot.server.Driver$delayedInit$body.apply(Driver.scala:13)
at scala.Function0.apply$mcV$sp(Function0.scala:34)
at scala.Function0.apply$mcV$sp$(Function0.scala:34)
at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
at scala.App.$anonfun$main$1$adapted(App.scala:76)
at scala.collection.immutable.List.foreach(List.scala:378)
at scala.App.main(App.scala:76)
at scala.App.main$(App.scala:74)
at org.activeintel.patentbot.server.Driver$.main(Driver.scala:13)
at org.activeintel.patentbot.server.Driver.main(Driver.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
Caused by: java.lang.ClassNotFoundException: scala.Product$class
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at play.api.libs.json.jackson.ReadingMap.<init>(JacksonJson.scala:108)
at play.api.libs.json.jackson.JsValueDeserializer.deserialize(JacksonJson.scala:153)
at play.api.libs.json.jackson.JsValueDeserializer.deserialize(JacksonJson.scala:120)
at play.api.libs.json.jackson.JsValueDeserializer.deserialize(JacksonJson.scala:115)
at com.fasterxml.jackson.databind.ObjectMapper._readValue(ObjectMapper.java:3779)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2050)
at play.api.libs.json.jackson.JacksonJson$.parseJsValue(JacksonJson.scala:238)
at play.api.libs.json.Json$.parse(Json.scala:21)
at org.activeintel.patentbot.server.Driver$.$anonfun$new$1(Driver.scala:35)
at org.activeintel.patentbot.server.Driver$.$anonfun$new$1$adapted(Driver.scala:28)
at scala.collection.Iterator.foreach(Iterator.scala:929)
at scala.collection.Iterator.foreach$(Iterator.scala:929)
at scala.collection.AbstractIterator.foreach(Iterator.scala:1406)
at scala.collection.IterableLike.foreach(IterableLike.scala:71)
at scala.collection.IterableLike.foreach$(IterableLike.scala:70)
at scala.collection.AbstractIterable.foreach(Iterable.scala:54)
at org.activeintel.patentbot.server.Driver$.delayedEndpoint$org$activeintel$patentbot$server$Driver$1(Driver.scala:28)
at org.activeintel.patentbot.server.Driver$delayedInit$body.apply(Driver.scala:13)
at scala.Function0.apply$mcV$sp(Function0.scala:34)
at scala.Function0.apply$mcV$sp$(Function0.scala:34)
at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
at scala.App.$anonfun$main$1$adapted(App.scala:76)
at scala.collection.immutable.List.foreach(List.scala:378)
at scala.App.main(App.scala:76)
at scala.App.main$(App.scala:74)
at org.activeintel.patentbot.server.Driver$.main(Driver.scala:13)
at org.activeintel.patentbot.server.Driver.main(Driver.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
[trace] Stack trace suppressed: run last compile:run for the full output.
java.lang.RuntimeException: Nonzero exit code: 1
at scala.sys.package$.error(package.scala:27)
[trace] Stack trace suppressed: run last compile:run for the full output.
[error] (compile:run) Nonzero exit code: 1
[error] Total time: 5 s, completed Dec 20, 2016 11:50:09 AM

 

 

keywords: pickle json case automatically reflection

7:28:55 PM SBT project import
[warn] Multiple dependencies with the same organization/name but different versions. To avoid conflict, pick one version:
[warn] * org.scala-lang:scala-reflect:(2.11.1, 2.11.6)

 

Searched for scala case class to json 7:15pm
  Implicit JSON conversion with Scala – chris-rock – lollyrock.com 7:12pm
  spray/spray-json · GitHub – github.com 7:12pm
  Parsing json with over 22 fields with… – pietrotull.com 7:12pm
  Scala macro annotations: a real-world… – kifi.com 7:12pm
Searched for scala infinite loop 7:14pm
Searched for Json.parse play implicit 7:02pm
  marshalling in Scala with Jackson – coderwall… – coderwall.com 7:01pm
  Play 2.1 Scala JSON parsing harder than… – stackoverflow.com 7:01pm
  Play 2.2.2 (Scala) Json parse as List[Class]… – stackoverflow.com 7:01pm
  Play JSON in Scala: intro and beyond… – xploregroup.be 7:02pm
  Play 2.3 client – Apidoc – apidoc.me
Searched for Json.parse play 7:00pm
  Working with JSON in Play 2.1 | Kifi… – kifi.com 7:01pm
New and Used Nissan Leaf: Prices, Photos,… – thecarconnection.com 5:25pm
Searched for play.api.libs.json as writes reads 4:29pm
  JSON Reads/Writes/Format Combinators… – playframework.com 4:29pm
  scala – serializing objects to json with… – stackoverflow.com

 

 

 

 

About Neil Rubens

see http://ActiveIntelligence.org

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*