How do you create Json object with values of different types? How do you create Json object with values of different types? json json

How do you create Json object with values of different types?


I agree with @alex23 that a case class based approach will be better. Using spray-json, you would first define your case class structure as well as an extension of DefaultJsonProtocol to describe the case classes you want to be able to serialize. That would look like this:

case class Image(link_path:String, display_name:String, size:Option[String],   modified:Option[String], thumbnail:String, filename:String, is_dir:Boolean, thumb_exists:Boolean)object Image  case class UrlImages(client:String, view:String, contents:List[Image])object UrlImagesobject MyJsonProtocol extends DefaultJsonProtocol {  implicit val imageFormat = jsonFormat8(Image.apply)  implicit val urlImagesFormat = jsonFormat3(UrlImages.apply)}  

Then, a modified version of your example would look like this:

import MyJsonProtocol._val images : List[Image] = fetchImageUrls(url).map((url: String) => {  Image(url, "image", None, None, url, "image", false, true)      })val jsonAst = UrlImages("urlimages", "thumbnails", images).toJson

The reason why you were seeing that error is that spray-json does not know how to serialize the Lists of tuples you are creating. If you really want to use that structure and not go the case class route, then you could look into providing a custom serializer for List[(String,Any)]. Check out the section in the spray-json docs titled "Providing JsonFormats for other Types". If you want to go this route and need more help, let me know.


You are going for the wrong approach here. For consistency purposes I would strongly encourage you to use a case class.

Say you have this

case class Image(    url: String,    size: Double,    properties: Map[String][String]    optionalProperty: Option[String]    // etc.);

And then you use parse and decompose to deal with this.

val image = parse(jsonString).extract[Image]; // extracts an Image from JSON.val jsonForImage: JValue = decompose(image);  // serializes an Image to JSON.

And if you want to serialize a List[Image] to JSON:

def serialize(images: List[Image]) : JValue = {    for (image <- images)        yield decompose(image);};

To parse a list of images from JSON:

val images: List[Image] = parse(jsonString).extract[List[Image]];

Using Option[SomeType] in the Image case class will deal with missing/optional parameters automatically.