在scala中将json对象的字符串转换为数组

时间:2018-10-23 12:28:57

标签: scala

我有以下字符串:

setConstraintHeight

,我想将其转换为数组:

[{"name":"Bob","age":"23"},{"name":"Alice","age":"31"},...]

我该如何实现?

2 个答案:

答案 0 :(得分:1)

那很容易。只需将JSON数组转换为Scala集合和映射名称即可。 例如。使用Circe:

public class AN {
  boolean flag;

  AN(boolean flag) {
    this.flag = flag;
  }

  synchronized void Alpha() throws InterruptedException {

    for(char i = 'A'; i <= 'Z'; i++) {
      while(flag == true) {
        wait();
      }
      System.out.println(i);
      notifyAll();
      flag = true;
    }
  }

  synchronized void numbers() throws InterruptedException {

    for(int i = 1; i <= 26; i++) {
      while(flag == false) {
        wait();
      }
      System.out.println(i);
      notifyAll();
      flag = false;
    }
  }

或者,如果可以的话,也可以通过JavaScript来完成。

答案 1 :(得分:0)

一种方法是使用Scala的内置JSON解析器。像这样的东西会起作用(尽管它可能会被重构):

import scala.util.parsing.json._

JSON.parseFull("""[{"name":"Bob","age":"23"},{"name":"Alice","age":"31"}]""") match {
  // get the head and tail of the List and check the head's type
  case Some((m: Map[_, _]) :: l) =>
      m.keys.headOption match {
        // match type of keys - maybe unnecessary but better safe than sorry
        case Some(_: String) =>
          // add the head back to the tail, get name values
          println((m +: l).asInstanceOf[List[Map[String, Any]]]
            .map(_.getOrElse("name", "")))
        case _ => ()
      }
    case _ => ()
}

在REPL中:

scala> import scala.util.parsing.json._
import scala.util.parsing.json._

scala> JSON.parseFull("""[{"name":"Bob","age":"23"},{"name":"Alice","age":"31"}]""") match {
     |   case Some((m: Map[_, _]) :: l) =>
     |       m.keys.headOption match {
     |         case Some(_: String) => println((m +: l).asInstanceOf[List[Map[String, Any]]].map(_.getOrElse("name", "")))
     |         case _ => ()
     |       }
     |     case _ => ()
     | }
List(Bob, Alice)
res0: Any = ()

但是,如果您已经验证了JSON的结构,则可以忽略所有类型验证-这些东西只是避免了类型不匹配时造成的麻烦(并且由于类型擦除而比理想情况更麻烦) )。

如果您使用Scala Play和case类(可以再次重构),将会容易得多:

import play.api.libs.json.{Json, OFormat}

case class Person(name: String, age: String)
object Person {
  implicit val format: OFormat[Person] = Json.format[Person]
}

Json.parse("""[{"name":"Bob","age":"23"},{"name":"Alice","age":"31"}]""")
  .asOpt[List[Person]] match {
  case Some(people) => println(people.map(_.name)) // List(Bob, Alice)
  case _ => println(Seq())
}