如何将给定JSON转换为目标数组?请求技术实现帮助
Got it, since you're working in Scala (given the val syntax), here are two solid ways to turn that JSON string into the arrays you need:
Approach 1: Quick, Direct Extraction (Play JSON)
This is the simplest path if you just need to pull out the values without strict type checking. First, make sure you have the Play JSON library added to your project (for sbt, add libraryDependencies += "com.typesafe.play" %% "play-json" % "2.9.2" to your build.sbt).
Then use this code:
import play.api.libs.json._ val inputJson = """[{"color": "red","value": "#f00"},{"color": "blue","value": "#00f"}]""" // Parse the JSON string into a JSON object val parsedJson = Json.parse(inputJson) // Extract all "color" values and convert to an Array val colorval: Array[String] = (parsedJson \\ "color").map(_.as[String]).toArray // Extract all "value" values and convert to an Array val value: Array[String] = (parsedJson \\ "value").map(_.as[String]).toArray // Check the results (optional) println(colorval.mkString("[", ", ", "]")) // Output: [red, blue] println(value.mkString("[", ", ", "]")) // Output: [#f00, #00f]
Approach 2: Type-Safe Extraction with Case Classes
For more robust code (great for larger projects or if your JSON structure might evolve), define a case class to match the JSON objects, then parse into a list of those classes before extracting the arrays:
import play.api.libs.json._ // Define a case class that mirrors the structure of each JSON object case class ColorEntry(color: String, value: String) // Create an implicit JSON reader to map JSON to the case class implicit val colorEntryReads: Reads[ColorEntry] = Json.reads[ColorEntry] val inputJson = """[{"color": "red","value": "#f00"},{"color": "blue","value": "#00f"}]""" // Parse the JSON into a list of ColorEntry instances val colorEntries: List[ColorEntry] = Json.parse(inputJson).as[List[ColorEntry]] // Extract the fields into your desired arrays val colorval: Array[String] = colorEntries.map(_.color).toArray val value: Array[String] = colorEntries.map(_.value).toArray
Both approaches will give you exactly the arrays you're looking for. The type-safe method helps catch parsing errors early and makes your code easier to maintain over time.
内容的提问来源于stack exchange,提问作者Rjj

