Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a HashMap using moshi

I'm trying to convert a HashMap of elements into a JSON string. I'm using the method used in this link.

 val elementsNew: HashMap<String, Element> = HashMap(elements)
 val type = Types.newParameterizedType(Map::class.java, String::class.java, Element::class.java)
 var json: String = builder.adapter(type).toJson(elementsNew)

But this gives the following error

Error:(236, 40) Type inference failed: Not enough information to infer parameter T in fun adapter(p0: Type!): JsonAdapter! Please specify it explicitly.

Can any one tell me where's the fault? Is it because of Kotlin?

like image 738
Sanka Darshana Avatar asked Dec 15 '17 04:12

Sanka Darshana


1 Answers

Looking at the signature of the adapter() method, it can't infer its type parameter from the argument:

public <T> JsonAdapter<T> adapter(Type type)

Hence you have to provide the type explicitly:

var json = builder.adapter<Map<String, Element>>(type).toJson(elementsNew)

or alternatively:

val adapter: JsonAdapter<Map<String, Element>> = builder.adapter(type)
var json = adapter.toJson(elementsNew)
like image 174
Egor Avatar answered Oct 05 '22 09:10

Egor