1

Given an example JSON object with a nested object who's properties are unkown:

      { "Key":"01234",
          "eventProperties":{
             "unknownProperty1":"value",
             "unknownProperty2":"value",
             "unknownProperty3":"value"
          },
       }

I have tried to use json4s' extract function with the following case class (In Scala):

case class nestedClass(Key:String, eventProperties:Map[(String,Any)])

Which results in the following error:

org.json4s.package$MappingException: Can't find constructor for nestedClass

Is it possible to do this without defining every possible property of eventProperties?

Update: there was a bug in json4s 3.2.10 causing this issue - updating to 3.2.11 and extracting to Map[String,Any] works fine.

2 Answers 2

2

I'm not sure what you are doing to get the exception you have posted, but the following works (note a Map instead of List):

import org.json4s._
import org.json4s.jackson.JsonMethods._
import org.json4s.DefaultFormats

val json = parse("""
{ "key":"01234",
  "eventProperties":{
    "unknownProperty1":"value",
    "unknownProperty2":"value",
    "unknownProperty3":"value"
  }
}
""")

case class NestedClass(key:String, eventProperties:Map[String,Any])

implicit val formats = DefaultFormats

json.extract[NestedClass]
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but using this I get: scala> org.json4s.package$MappingException: No usable value for eventProperties No information known about type
Turns out there's a bug in 3.2.10 that's the problem - 3.2.11 fixed it
if you plan to serialize more complicated stuff, I suggest using Jackson + Scala plugin for serialization/deserialization. Last time I checked it was supporting a larger subset of Scala constructs than json4s. json4s using Jackson internally anyways.
0

In Order to get eventProperties as List[(String, Any)], your json should be,

         """ {
               "key": "01234",
               "eventProperties": [
                   {"unknownProperty1": "value"},
                   {"unknownProperty2": "value"},
                   {"unknownProperty3": "value"}
               ]
           }"""

Otherwise, you can use Map instead of List as case class nestedClass1(key:String, eventProperties:Map[String,Any]) and then convert to nestedClass as nestedClass( n1.key, n1.eventProperties.toList)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.