Storing hashmap to consul using scala

Hi all,

I am trying to store a hashmap consisting of a byte value and a list to consul.

I am partially successful but I am getting the following error:

“Any does no take any parameters”

Here is my code:

--------- to form a byte array-------------------
import java.io.ByteArrayOutputStream
import java.io.ObjectOutputStream

val bos = new ByteArrayOutputStream
val out = new ObjectOutputStream(bos)
out.writeObject(list)
val yourBytes = bos.toByteArray

------------ to form a list-------------
val list = new util.ArrayListString
list.add(“a”)
list.add(“aa”)

----------- to create a map ----------------
var map = new util.HashMapString,Any
map.put(“query”, yourBytes)
map.put(“abc”,list)

------------ to create a json and put the json object in consul--------------

implicit def PersonEncodeJson: EncodeJson[util.HashMap[String,Any]] =
EncodeJson((p: util.HashMap[String,Any]) => (“query” := p.get(“query”)(AnyRef)) ->: (“dimension” := p.get(“abc”)(AnyRef)) ->: jEmptyObject)

AnyRef is giving me the above error.
If I don’t write it, it gives me "No implicits found for parameter EncodeJson[Any] "

----- remaining code-------
val json: Json =map.asJson(PersonEncodeJson: EncodeJson[util.HashMap[String,Any]])

val prettyprinted: String =json.spaces2
println(prettyprinted)

private val client = new ConsulClient(“localhost”)

client.setKVValue(“STIP_1.0”, prettyprinted)


1 Like

Dear Tushar,

You need to use Scala types for the JSON encoder to work better, here you have a whole functional project where I try to serialize with json4s:

NOTE: if you decide to clone the repo locally in your computer, please notice that your sample code is at the branch storing-hashmap-to-consul-using-scala

As a reference here you have the snippet code of the main part ->

package cs.scala.json.parser.sample

import java.nio.charset.StandardCharsets

import org.json4s.DefaultFormats
import org.json4s.jackson.Serialization

object CsScalaJsonParserSampleApp extends App {

  implicit val json4sFormats = DefaultFormats
  
  val yourBytes: Array[Byte] = "somebytes".getBytes(StandardCharsets.UTF_8)

  val list: List[String] = List("a", "aa")

  val map = Map("query" -> yourBytes, "abc" -> list)

  val json = Serialization.writePretty(map)

  println(json)

}

The output is:

{
  "query" : [ 115, 111, 109, 101, 98, 121, 116, 101, 115 ],
  "abc" : [ "a", "aa" ]
}

IMPORTANT: here json4s decided to serialize the bytes as an array of integers in JSON, if this is not supported nor expected by Consul, you may convert the array of bytes to any format Consul is expecting as the intermediate json to this to work … by instance, if Consul expects all the bytes as hexadecimal numbers but in a string separed by collons, just do that at scala side and let the json4s just converte it as a normal string after that.