【问题标题】:How to serialize an array of objects to a JSON JValue?如何将对象数组序列化为 JSON JValue?
【发布时间】:2011-10-16 09:09:42
【问题描述】:

有一个对象数组,我想将它们序列化为 JSON(一个 JValue 实例)。 我尝试了以下两种组合 JSON 实体的变体:


def items : Array[FooBar] = Array (new FooBar(1), new FooBar(2), new FooBar(3))
def toJson : JValue = {
  val jItems : Array[JValue]= items.map(i => i.toJson)

  // variant 1.
  // val jItemsC = jItems.reduceLeft[JValue](_~_)

  // variant 2.
  val jItemsC = jItems.reduceLeft((a : JObject, b : JValue) => a ~ b)

  "items" -> jItemsC
}

第一个(和第二个(a:JValue,b:JValue))说 value ~ is not a member of net.liftweb.json.package.JValue

第二个说 overloaded method value ~ with alternatives: (right: net.liftweb.json.package.JObject)net.liftweb.json.JsonAST.JObject <and>
(right: (String, net.liftweb.json.package.JValue))net.liftweb.json.JsonAST.JObject
cannot be applied to (net.liftweb.json.package.JValue)

那么问题是什么,我的问题如何解决?

【问题讨论】:

    标签: arrays json scala lift


    【解决方案1】:

    这些应该可以工作:

    val a = Array("a", "b", "c")
    Extraction.decompose(a)
    

    JArray(a.toList map JString.apply)
    

    【讨论】:

    • Extraction.decompose(a)(其中 a 是我的一个类的实例数组)导致 could not find implicit value for parameter formats: net.liftweb.json.Formats 编译错误。
    • JArray(a.toList map JString.apply) 导致 type mismatch; found : String =&gt; net.liftweb.json.JsonAST.JString; required: code.model.Item =&gt; ? 编译错误。
    • 当 a 是 JValue 对象数组时,JArray(a.toList) 似乎可以工作(至少可以编译)。
    猜你喜欢
    • 2021-05-29
    • 2014-01-28
    • 2020-03-05
    • 2014-03-05
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多