最近开始使用json4s来解析和生成JSON。
引入依赖
<dependency>
<groupId>org.json4s</groupId>
<artifactId>json4s-jackson_2.10</artifactId>
<version>3.2.11</version>
</dependency>
构造JSON字符串
例1
implicit val formats = Serialization.formats(ShortTypeHints(List()))
val str: JsonAST.JObject =
("property_name" -> "三聚氰胺(mg/kg)") ~ ("property_result" -> "阴性")
println(compact(render(str)))
输出为
{“property_name”:”三聚氰胺(mg/kg)”,”property_result”:”阴性”}
注意:如果这里没有引入一个implicit format,会报错:
No org.json4s.Formats found. Try to bring an instance of org.json4s.Formats in scope or use the org.json4s.DefaultFormats.
例2
implicit val formats = Serialization.formats(ShortTypeHints(List()))
val str: List[JsonAST.JObject] = List(
("property_name" -> "三聚氰胺(mg/kg)") ~ ("property_result" -> "阴性"),
("property_name" -> "铬(mg/kg)") ~ ("property_result" -> "0.022") )
println(compact(render(str)))
输出结果为
[{“property_name”:”三聚氰胺(mg/kg)”,”property_result”:”阴性”},{“property_name”:”铬(mg/kg)”,”property_result”:”0.022”}]