如何创建具有不同类型值的 Json 对象? [英] How do you create Json object with values of different types?

查看:61
本文介绍了如何创建具有不同类型值的 Json 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建具有不同类型值的 Json 对象?

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

我正在使用spray-json

I'm using spray-json

这是代码

val images : List[JsObject] = fetchImageUrls(url).map((url: String) => {
  JsObject(List(
        "link_path" -> JsString(url),
        "display_name" -> JsString("image"),
        "size" -> JsString(""),
        "modified" -> JsString(""),
        "thumbnail" -> JsString(url),
        "filename" -> JsString("image"),
        "is_dir" -> JsBoolean(x = false),
        "thumb_exists" -> JsBoolean(x = true)) )
  })

val jsonAst: JsObject = JsObject(List(
  "client" -> JsString("urlimages"),
  "view" -> JsString("thumbnails"),
  "contents" -> JsArray(images)
))

它可以工作,但看起来很重.有没有办法用这样的代码定义json?

It works but looks really heavy. Is there a way to define json with code like this ?

val images : List[List[(String, Any)]] = fetchImageUrls(url).map((url: String) => {
  List(
    "link_path" -> url,
    "display_name" -> "image",
    "size" -> "",
    "modified" -> "",
    "thumbnail" -> url,
    "filename" -> "image",
    "is_dir" -> false,
    "thumb_exists" -> true)
})

val jsonAst = List(
  "client" -> "urlimages",
  "view" -> "thumbnails",
  "contents" -> images
).toJson

这样说是行不通的

Cannot find JsonWriter or JsonFormat type class for List[(String, Object)]
    ).toJson
      ^

我得到的是,每个字段的类型在编译时没有定义.但是,如果序列化程序无论如何都进行模式匹配,为什么它不起作用?

Which I get, type of each field is not defined at compile time. But why wouldn't it work if serializer does pattern matching anyway ?

谢谢!

推荐答案

您在这里采用了错误的方法.为了保持一致性,我强烈建议您使用 case class.

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

说你有这个

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

然后你使用 parsedecompose 来处理这个.

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.

如果您想将 List[Image] 序列化为 JSON:

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

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

从 JSON 解析图像列表:

To parse a list of images from JSON:

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

Image case class 中使用 Option[SomeType] 会自动处理缺失/可选参数.

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

这篇关于如何创建具有不同类型值的 Json 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆