Tags down


Not extracting json properly using json4s

By : Cesar
Date : October 18 2020, 06:10 AM
it helps some times Here is a way to do so, using the apply method on the JArray:
code :
import org.json4s._
import org.json4s.native.JsonMethods._

val json = parse("""{"key1":["12345"],"key2":[{"key3":"some value"}]}""")
(json \ "key2" )(0) \ "key3"
// res6: JValue = JString("some value")

Share : facebook icon twitter icon

Flatten extranous fields when extracting using LiftJson or Json4s

By : Avia Barsik
Date : March 29 2020, 07:55 AM
seems to work fine I found the solution a while ago, but haven't had time to reply. I was thinking backward, this is easy:
code :
def transformListData(src: JValue, field: String): JValue = {
  src.transformField {
    case JField(x, v) if x == field => JField(field, v \ "data")

transformListData(json, "comments")

[json4s]:Extracting Array of different objects

By : user2349404
Date : March 29 2020, 07:55 AM
it fixes the issue A possibility I found was to use more case classes instead of inheritance:
code :
case class Root[T](data:Option[T])
case class Post(id: String, from: From, message: String)
case class From(id: String, name:String)
val body = r.entity.asString
val json = parse(r.entity.asString)
val root = json.extract[Root[Post]]

root.data match {
  case Some(post) =>
      val tagger = Tagger(post.from.id, post.from.name, post.id, post.message)
      log.info(s"We received $tagger")
      originalSender ! RetrievedTagger(tagger)

  case None => originalSender ! NoTaggerFound

Extracting polymorphic types in json4s

By : Matrica
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further Ultimately, on the project that lead to this question, I agreed with the guy creating the serialized JSON on adding type hints for all polymorphic types. In retrospect this solution is probably the cleanest because it enables future extension of the JSON schema without dangers of introducing ambiguity.
Nevertheless, there exists a fairly simple solution (not just a workaround) to the actual problem.
code :
trait Animal
case class Dog(name: String) extends Animal
case class Bird(canFly: Boolean) extends Animal
class AnimalSerializer extends CustomSerializer[Animal](format => ( {
  case JObject(List(JField("name", JString(name)))) => Dog(name)
  case JObject(List(JField("canFly", JBool(canFly)))) => Bird(canFly)
}, {
  case Dog(name) => JObject(JField("name", JString(name)))
  case Bird(canFly) => JObject(JField("canFly", JBool(canFly)))
case class AnimalList(animals: List[Animal])

val json =
    |{"animals": [
    |  {"name": "Pluto"},
    |  {"name": "Goofy"},
    |  {"canFly": false},
    |  {"name": "Rover"}
    |  ]
implicit val format = Serialization.formats(NoTypeHints) + new AnimalSerializer
AnimalList(List(Dog(Pluto), Dog(Goofy), Bird(false), Dog(Rover)))

extracting keys from json string using json4s

By : 张小萌
Date : March 29 2020, 07:55 AM
To fix this issue can someone tell me how to extract keys from json using json4s. My use case: json stored as string in scala variable:
code :
val result: Map[String, String] = parse( """ {
                                           | "key1" : "val1",
                                           | "key2" : ["12", "32"],
                                           | "key3" : {"keyN" : "valN"}
                                           | }""".stripMargin).mapField(k => {
  val v: String = k._2 match {
    case s: JString => k._2.extract[String]
    case _ => write(k._2)
  (k._1, JString(v))
}).extract[Map[String, String]]

json4s org.json4s.package$MappingException: Do not know how to convert JString into double

By : Huge Gin Amganakikyu
Date : March 29 2020, 07:55 AM
wish help you to fix your issue I am trying a very simple example, but not able to make it work; Below is my JSON format, I am using the Scala json4s parser for parsing JSON; json4s fails to parse a JSON string if any JSON field is not a string. For example json4s fails to parse field_3 as double and field_4 as int. , I have solved this problem using something like:
code :
case class TestClassHelper(field_1: String, field_2: String, field_3: String, field_4: String) {
    def toTestClass: TestClass(field_1, field_2, field_3.toDouble, field_4.toInt)

val infoTemp: List[TestClassHelper] =JSON.extract[List[TestClassHelper]]
val info: List[TestClass] = infoTemp.map(_.toTestClass())
Related Posts Related Posts :
  • Convert hashmap to simple object in Groovy
  • Break JSON in pager "less"
  • How to filter Map in Flutter?
  • Spark How to get number of Keys changed in two JSONS in Scala?
  • read json and access multiple keys
  • can Kafka connect value conveter (JSONConverter) can be used to convert GPB?
  • 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
  • Extract Badge ID from JSON in .gitlab-ci.yml
  • Open JSON files in PhpStorm built-in web server
  • Initializing and inserting nested JSON data in Golang?
  • kubectl - format the resource quota values in json format
  • Type 'number' is not assignable to type 'string'. How to cast number to string
  • Nested json extract from powershell
  • Parsing Json using Golang
  • json_to_record with embedded encoded json in PostgreSQL >= 10
  • Incorrect type. Expected "object"
  • Extracting specific and latest data from http webserver using golang
  • How to validate JSON input in Go
  • How to get the value of a key in a JSON?
  • Storing JSON in BigQuery
  • Issue sending POST request from Swift
  • How to concat multiple fields to same line with jq
  • AWS CloudFormation Template (JSON) to Create EC2 - Unexpected Error
  • Reading JSON data for my select query in SQL Server
  • Difficulty fetching json data from API using Angular
  • How to send Map as String in POST request in flutter?
  • Getting _jsonparsefailure with valid json in logstash
  • detecting 400 response without JSON response
  • Newtonsoft deserializing Json incorrectly
  • JSON syntax for getting personal query ID
  • How to parse JSON-input
  • How to remove brakets on Json respone
  • JSON decode failed
  • Unable to render data into grid column using JSON results
  • Modifying settings.json in vscode to add shell escape flag to pdflatex in latex workshop
  • Getting key value pairs with linux server
  • Output key value pairs as JSON from T-SQL query
  • How not to allow empty fields when Unmarshalling json to a struct
  • Saving an array in JSON in ionic
  • How to return three objects into one object in java?
  • How to get json array from json object in SWIFT?
  • kubectl apply error: error converting YAML to JSON
  • .NET Core Model Not Binding
  • Convert json repsonse to strings and put it in a structure
  • How to take info from sub-object in request before validating in Django?
  • jq: concatenate two values from data set
  • How to merge data in a json by a name property in typescript
  • How do I update JSON file using PowerShell (Patch Method)
  • I can't get the data in appends with json in Laravel
  • fetching json data from local file
  • Summing JSON values
  • HTTP GET with request body to limit fields and filter
  • Angular 7 correct way to check if JSON parse returns a specific object
  • Flutter get Data from complex json
  • Remove backslashes from JSON SQL Query
  • jq: Object cannot be csv-formatted, only array
  • Access field of type after Json decode in elm
  • Mule Dataweave - Add Nested and Simple attributes
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk