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?

P3trur0
3,2251 gold badge15 silver badges27 bronze badges
asked Nov 15, 2018 at 16:19

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])
answered Nov 15, 2018 at 16:28
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)
answered Nov 15, 2018 at 16:38

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.