scala 将Scala列表转换为Json对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15497598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 05:04:10  来源:igfitidea点击:

Convert scala list to Json object

jsonlistscala

提问by malmling

I want to convert a scala list of strings, List[String], to an Json object.

我想将 Scala 字符串列表 List[String] 转换为 Json 对象。

For each string in my list I want to add it to my Json object.

对于列表中的每个字符串,我想将其添加到我的 Json 对象中。

So that it would look like something like this:

所以它看起来像这样:

{
 "names":[
  {
    "Bob",
    "Andrea",
    "Mike",
    "Lisa"
  }
 ]
}

How do I create an json object looking like this, from my list of strings?

如何从我的字符串列表中创建一个看起来像这样的 json 对象?

回答by Impredicative

To directly answer your question, a very simplistic and hacky way to do it:

要直接回答您的问题,这是一种非常简单和 hacky 的方法:

val start = """"{"names":[{"""
val end = """}]}"""
val json = mylist.mkString(start, ",", end)

However, what you almost certainly want to do is pick one of the many JSON libraries out there: play-jsongets some good comments, as does lift-json. At the worst, you could just grab a simple JSON library for Java and use that.

但是,您几乎肯定想要做的是从众多 JSON 库中选择一个:play-json得到了一些好评,lift-json 也是如此。在最坏的情况下,您可以只获取一个简单的 Java JSON 库并使用它。

回答by Dylan

Since I'm familiar with lift-json, I'll show you how to do it with that library.

由于我熟悉lift-json,我将向您展示如何使用该库进行操作。

import net.liftweb.json.JsonDSL._
import net.liftweb.json.JsonAST._
import net.liftweb.json.Printer._
import net.liftweb.json.JObject

val json: JObject = "names" -> List("Bob", "Andrea", "Mike", "Lisa")

println(json)
println(pretty(render(json)))

The names -> List(...)expression is implicitly converted by the JsonDSL, since I specified that I wanted it to result in a JObject, so now jsonis the in-memory model of the json data you wanted.

names -> List(...)表达式由 JsonDSL 隐式转换,因为我指定我希望它产生 a JObject,所以现在json是您想要的 json 数据的内存模型。

prettycomes from the Printerobject, and rendercomes from the JsonASTobject. Combined, they create a Stringrepresentation of your data, which looks like

pretty来自Printer对象,render来自JsonAST对象。结合起来,它们创建了String您的数据的表示,看起来像

{
  "names":["Bob","Andrea","Mike","Lisa"]
}

Be sure to check out the lift documentation, where you'll likely find answers to any further questions about lift's json support.

请务必查看提升文档,您可能会在其中找到有关提升的 json 支持的任何其他问题的答案。