3

I want to parse a Json Object. I have defined the following class:

case class Metadata(
  val messageTime:   Option[String], 
  val messageUUID:   Option[String], 
  val messageSource: Option[String], 
  val messageFormat: Option[String])

I generate a dummy object of this type:

jsonMsg = """{"messageTime": "2018-09-19T11:03:22.382+04:00", 
 "messageUUID": "4ef7fce7-81cf-4a27-82d8-9019c2cf09df", 
 "messageSource" : "SDG", 
 "messageFormat" : "json"}"""

Now I want to use mapper.readValue to parse that string into an Object of type Metadata:

fromJson(jsonMsg) 

def fromJson(json : String)  = {
mapper.readValue[Metadata](json, classOf[Metadata])
}

This works fine. But in this case fromJson can only parse Metadata objects.

Now I tried to make my method fromJson more generic, passing the class of the object to be parsed like this [I used this other question as a reference ]:

val obj = fromJson2(jsonMsg, classOf[Metadata])

def fromJson2(json : String, c: Class[_])  = {
  mapper.readValue(json, c)
}

But I get the error:

forward reference extends over definition of value obj

What am I missing or how could I achieve what I am trying?

Just in case mapper.readValue belongs to import com.fasterxml.jackson.databind.ObjectMapper

And this is the definition:

public <T> T readValue(String content, Class<T> valueType)
    throws IOException, JsonParseException, JsonMappingException
{
    return (T) _readMapAndClose(_jsonFactory.createParser(content), _typeFactory.constructType(valueType));
} 
Ignacio Alorre
  • 7,307
  • 8
  • 57
  • 94
  • 1
    What is the `obj` that the error message complains about? Show more complete code. – Thilo May 16 '19 at 10:41
  • @Thilo it is the ouput of the call to fromJson2. I will edit – Ignacio Alorre May 16 '19 at 10:48
  • Is that really `Val` with a capital `V` ? Does moving the definition of `fromJson2` ahead of its use help (that is usually what "forward reference" talks about)? – Thilo May 16 '19 at 10:54
  • 1
    @Thilo it was that... didnt expect the order matters in scala. Such a long question for such a silly mistake. Thanks a lot Thilo! – Ignacio Alorre May 16 '19 at 11:35

0 Answers0