Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert HashMap to JSON in Kotlin

I have HashMap in Kotlin

val map = HashMap<String, String>()
map.put("key1","value1");
map.put("key2","value2");
map.put("key3","value3");

How to convert it into String in JSON format? like

{"key1": "value1", "key2": "value2", "key3": "value3"}
like image 511
Asad Ali Choudhry Avatar asked Jun 10 '19 11:06

Asad Ali Choudhry


People also ask

How do I convert maps to Gson?

By using new Gson(). By creating a GsonBuilder instance and calling with the create() method.

What is map in JSON?

A JSONObject is an unordered collection of name/value pairs whereas Map is an object that maps keys to values. A Map cannot contain duplicate keys and each key can map to at most one value. We need to use the JSON-lib library for serializing and de-serializing a Map in JSON format.

What is JSON hash?

A Hash is a sparse array that uses arbitrary strings/objects (depending on the implementation, this varies across programming languages) rather than plain integers as keys. In Javascript, any Object is technically a hash (also referred to as a Dictionary, Associative-Array, etc).


1 Answers

You can use org.json which is shipped with Android:

JSONObject(map).toString()
like image 90
Miha_x64 Avatar answered Sep 17 '22 18:09

Miha_x64