1

I have list of elements containing product name val productList = List[String] with values as product1,product2,product3

now I need to create a Json from the list as

{
   "ProductName":["product1","product2","product3"]
}

how can I achieve this using scala json4s framework.

2 Answers 2

3

You may also try write method.

import org.json4s._
import org.json4s.jackson.Serialization.write
import org.json4s.jackson.JsonMethods._
implicit val formats = DefaultFormats
val json = write(Map("productList" -> productList))
Sign up to request clarification or add additional context in comments.

Comments

0

You should be able to render the list directly. Json4s can implicitly convert a list of strings into a JArray, which then becomes a json list.

import org.json4s._
import org.json4s.JsonDSL._
import org.json4s.jackson.JsonMethods._

val productList: List[String] = List("product1", "product2", "product3")
val obj: JObject = ("ProductName" -> productList)
compact(render(obj))
//res1: String = {"ProductList":["product1","product2","product3"]}

The readme for Json4s has some similar examples.

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.