0

I'm trying to use a Jackson's ObjectMapper() function: convertValue.

It takes 2 parameters (3 overloads):

  1. (Object, Call)
  2. (Object, TypeReference)
  3. (Object, JavaType)

I have the following code:

val m = new ObjectMapper()
val map: Map[String, Object] = m.convertValue(bean, classOf[Map])

which doesn't work with error Type Mismatch. Expected JavaType actual Class[Map].

I tested with classOf[java.util.Map], Map.getClass, etc. but can't make it work.

How should I send that parameter?

2 Answers 2

1

Step 1: look at https://fasterxml.github.io/jackson-databind/javadoc/2.8/com/fasterxml/jackson/databind/JavaType.html. See

Instances can (only) be constructed by com.fasterxml.jackson.databind.type.TypeFactory.

Step 2: look at https://fasterxml.github.io/jackson-databind/javadoc/2.8/com/fasterxml/jackson/databind/type/TypeFactory.html.

Then you can see it can be used as e.g.

m.getTypeFactory.constructMapType(classOf[java.util.Map[_, _]], classOf[YourKey], classOf[YourValue])
Sign up to request clarification or add additional context in comments.

1 Comment

This throws me: java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to scala.runtime.Nothing$
0

You can use the mapper to get the JavaType, for example:

val stringType:JavaType  = mapper.constructType(String.class);

You can try the following for your problem:

val m = new ObjectMapper()
val mapType:JavaType = mapper.constructType(java.util.Map.class)
val map: Map[String, Object] = m.convertValue(bean, mapType)

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.