konquestor
konquestor

Reputation: 1308

Deserialize Scala deserialized object in Java

======Update=====

For Scala class with Jackson annotation can be serialized in Java.

case class B @JsonCreator()(@JsonProperty("test")test: Boolean)

This works (takes care of the earlier problem). However if i use Option[Boolean]..

case class B @JsonCreator()(@JsonProperty("test")test: Option[Boolean])

Java Code to deserialize

mapper.readValue("{\"test\": false}", B.class);

throws exception

com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of scala.Option, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information

=== Update end ====

I have Scala classes, which are serialized using Play json and sent over rest service. I want to deserialize this json in my Java program using the Scala class. To clarify with example:

//A.scala
package my.scala
class A (test: Boolean)

//B.scala
package my.scala

case class B(test: Boolean)


//MyProg.java
package my.java
import com.fasterxml.jackson.databind.ObjectMapper;
public class MyProg {

ObjectMapper mapper = new ObjectMapper();
mapper.readValue("{\"test\": false}", A.class);

//this one too fails.
//mapper.readValue("""{"test": false}""", B.class);
}

I get following exception on mapper.ReadValue

com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class my.java.A]: can not instantiate from JSON object (need to add/enable type information?)
 at [Source: {
  "test": false
}; line: 2, column: 3]
    at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)

My primary objective was to deserialized case class. However i read that case class cannot be deserialized without adding jackson annotation @JSONCreator, i tired adding that, but that did not work either.

I then tried using regular scala class, but that is not working either. How do i go about using my deserialized scala classes in java?

Upvotes: 2

Views: 1310

Answers (1)

konquestor
konquestor

Reputation: 1308

I resolved the issue by registering ScalaModule to my object mapper

//MyProg.java
package my.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.module.scala.DefaultScalaModule;

public class MyProg {

ObjectMapper mapper = new ObjectMapper().registerModule(new DefaultScalaModule());

mapper.readValue("{\"test\": false}", A.class);

mapper.readValue("""{"test": false}""", B.class);
}

@JacksonCreatoer and @JacksonProperty annotation on the scala object was needed.

Upvotes: 1

Related Questions