logo
down
shadow

Having trouble getting Writes to work with Scala Play


Having trouble getting Writes to work with Scala Play

By : Adamfazai
Date : November 16 2020, 12:01 PM
help you fix your problem To begin with I would like to say sorry for long post, and I really appreciate those who still look into my problem. ,
Just put the implicit val class3Writer ahead of class2Writes
code :


Share : facebook icon twitter icon
How to write Reads[T] and Writes[T] in scala Enumeration (play framework 2.1)

How to write Reads[T] and Writes[T] in scala Enumeration (play framework 2.1)


By : Benny
Date : March 29 2020, 07:55 AM
I wish this helpful for you Short answer: use something like Play Enumeration Utils.
Long answer, instead of putting a Reads in your enum, you can create a re-useable Reads for Enumeration types:
code :
object EnumA extends Enumeration {
  type EnumA = Value
  val VAL1, VAL2, VAL3 = Value
}

object EnumUtils {
  def enumReads[E <: Enumeration](enum: E): Reads[E#Value] = new Reads[E#Value] {
    def reads(json: JsValue): JsResult[E#Value] = json match {
      case JsString(s) => {
        try {
          JsSuccess(enum.withName(s))
        } catch {
          case _: NoSuchElementException => JsError(s"Enumeration expected of type: '${enum.getClass}', but it does not appear to contain the value: '$s'")
        }
      }
      case _ => JsError("String value expected")
    }
  }
}
import some.thing.EnumUtils
implicit val myEnumReads: Reads[EnumA.Value] = EnumUtils.enumReads(EnumA)

val myValue: EnumA.Value = someJsonObject.as[EnumA.Value]
val myValue: EnumA.Value = someJsonObject.asOpt[EnumA.Value].getOrElse(sys.error("Oh noes! Invalid value!"))
object EnumUtils {
  ...
  implicit def enumWrites[E <: Enumeration]: Writes[E#Value] = new Writes[E#Value] {
    def writes(v: E#Value): JsValue = JsString(v.toString)
  }
}
import EnumUtils.enumWrites
val myEnumJson: JsValue = Json.toJson(EnumA.VAL1)
object EnumUtils {
  ....
  implicit def enumFormat[E <: Enumeration](enum: E): Format[E#Value] = {
    Format(EnumReader.enumReads(enum), EnumWriter.enumWrites)
  }
}
Generic way to implement a Pk Writes in Play Scala

Generic way to implement a Pk Writes in Play Scala


By : Peaceful_Warrior
Date : March 29 2020, 07:55 AM
will be helpful for those in need The only thing you need to do is ensuring that there is deserializer for type E in scope, because now you can't be sure that each type you use is writeable. You can try it:
code :
class Value[A](value: A){
  def get[A] = value
}

implicit def valueWrites[E](implicit longWrites: Writes[E]) = new Writes[Value[E]]{
    def writes(value: Value[E]): JsValue = Json.toJson(value.get)
}

Json.toJson(new Value(5L))
implicit def valueToJson[E: Writes] = new Writes[Value[E]]{
    def writes(value: Value[E]): JsValue = Json.toJson(value.get)
}
Serialize set to json with a custom Writes in Scala Play 2.4

Serialize set to json with a custom Writes in Scala Play 2.4


By : karoles
Date : March 29 2020, 07:55 AM
wish help you to fix your issue You are reimplementing writes for traversable that are trivial anyway but still. Another option is to reuse that Writes
code :
val users: Set[User] = ???
Json.toJson(users)(Writes.traversableWrites(userSafeWrites))
implicit def traversableWrites[A: Writes] = Writes[Traversable[A]] { as =>
  JsArray(as.map(toJson(_)).toSeq)
}
case class User(num: Int)

object User {
  implicit val writes = Json.writes[User]
}
object OtherWrites {
  implicit val custom: Writes[User] = new Writes[User] {
    override def writes(o: User): JsValue = JsNull
  }
}
object Client extends App {
  val obj = List(User(1))
  print(Json.toJson(obj))
}
object Client extends App {
  import test.OtherWrites._
  val obj = List(User(1))
  print(Json.toJson(obj))
}
Scala Compiler (2.11.7) anomaly with Play JSON Writes

Scala Compiler (2.11.7) anomaly with Play JSON Writes


By : Sunil kumar
Date : March 29 2020, 07:55 AM
Hope this helps I am pretty sure the issue comes from .getOrElse(JsNull)
I have successfully compiled this code:
code :
import play.api.libs.json.{JsNull, Json, JsValue, Writes}

case class Cost(cost: Option[Double])

case object Cost {
  def writes = new Writes[Cost] {
    override def writes(r: Cost): JsValue = {
      Json.obj(
        "cost" -> r.cost.map(Json.toJson(_))
      )
    }
  }
}
scala> Cost(Some(5))
res2: Cost = Cost(Some(5.0))

scala> Json.toJson(res2)(Cost.writes)
res5: play.api.libs.json.JsValue = {"cost":5}
val cost = r.cost.map(t => Json.toJson(t))
Json.obj(
  "cost" -> cost
)
cost.getOrElse[JsValue](JsNull)
cost.getOrElse(JsNull).asInstanceOf[JsValue]
[error] (...) type mismatch;
[error]  found   : Object
[error]  required: play.api.libs.json.Json.JsValueWrapper
Scala Play Json implicit writes type mismatch

Scala Play Json implicit writes type mismatch


By : Jared Weinfurtner
Date : March 29 2020, 07:55 AM
I wish did fix the issue. You're trying to serialize the type Subscription, rather than the request body, which you stored as the value subscription. Try replacing the last line with Ok(Json.toJson(subscription)).
Related Posts Related Posts :
  • how to write r.headers from different urls into one json?
  • Parsing JSON concurrently - panic of runtime error (decoding related)
  • How to fix "Subscript out of range" error in XML HTTP Request
  • Splitting nested arrays as separate entities
  • Trying to parse the JSON and create an extracted JSON
  • NiFi JoltTransformJson outputs only first record
  • Dynamic (But known as another key value) JSON Decoding with Swift Decodable
  • How to use map on json response returned by a REST API with ReactJs
  • How to read a file line by line and then output all lines compounded with sth in jq?
  • java.lang.RuntimeException: Failed : HTTP error code : 400 : Bad Request
  • How to check jq result is null or not?
  • CloudFormation - How to use Sub intrinsic function?
  • VBA: Nested JSON Object Structure for UK Bank Holidays - Run Time Errors 13, 438 and 449
  • JasperReports. Using value from parent json in child table
  • Output key value pairs as JSON from T-SQL query
  • Getting key value pairs with linux server
  • Modifying settings.json in vscode to add shell escape flag to pdflatex in latex workshop
  • Unable to render data into grid column using JSON results
  • JSON decode failed
  • How to remove brakets on Json respone
  • How to parse JSON-input
  • JSON syntax for getting personal query ID
  • detecting 400 response without JSON response
  • Newtonsoft deserializing Json incorrectly
  • Getting _jsonparsefailure with valid json in logstash
  • How to send Map as String in POST request in flutter?
  • Difficulty fetching json data from API using Angular
  • Reading JSON data for my select query in SQL Server
  • AWS CloudFormation Template (JSON) to Create EC2 - Unexpected Error
  • How to concat multiple fields to same line with jq
  • Issue sending POST request from Swift
  • Storing JSON in BigQuery
  • How to get the value of a key in a JSON?
  • How to validate JSON input in Go
  • Extracting specific and latest data from http webserver using golang
  • Incorrect type. Expected "object"
  • json_to_record with embedded encoded json in PostgreSQL >= 10
  • Nested json extract from powershell
  • Parsing Json using Golang
  • Type 'number' is not assignable to type 'string'. How to cast number to string
  • kubectl - format the resource quota values in json format
  • Initializing and inserting nested JSON data in Golang?
  • Open JSON files in PhpStorm built-in web server
  • Extract Badge ID from JSON in .gitlab-ci.yml
  • Sharing Json Schema files among projects with versioning
  • Export Json data to an excel file using Angular 4
  • Return an empty array instead of null with golang for json return with gin
  • can Kafka connect value conveter (JSONConverter) can be used to convert GPB?
  • read json and access multiple keys
  • Spark How to get number of Keys changed in two JSONS in Scala?
  • Break JSON in pager "less"
  • How to filter Map in Flutter?
  • Convert hashmap to simple object in Groovy
  • Not extracting json properly using json4s
  • How do I display JSON data in my tableView when objects have the same value?
  • Where I can parse IoT data in Azure so I can afterwards save it to SQL DB
  • How to unmarshal this json string
  • What's wrong with my JSON?
  • JSON parsing problem in BlackBerry
  • GWT: How can I use JsonpRequestBuilder to handle a Json response of a list
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org