我有一个像这样的json:
[
{
"firstName":"Pierre",
"age":"20",
"timestamp": "123"
},
{
"firstName":"Jack",
"age":"20",
"timestamp": "123"
},
{
"firstName":"Olive",
"age":"20",
"timestamp": "123"
},
{
"firstName":"Tom",
"age":"20",
"timestamp": "123"
}
]
我想将所有属性timestamp更新为456.然后我创建一个这样的代码:
import org.json.simple.{JSONArray, JSONObject}
myJsonArray.forEach {
obj =>
val jsonObject = obj.asInstanceOf[JSONObject]
val jsonMap = jsonObject.asInstanceOf[java.util.HashMap[String,Any]]
jsonMap.put("timestamp",456)
}
但我参与编译:
Error:(31, 7) missing parameter type
obj =>
你知道吗?还是其他任何实施?
答案 0 :(得分:1)
您的JSON已损坏,"age":"20"
字段后应该有一个逗号。
因此,在更正它之后,您可以使用以下内容来更新您的JSON。在这里,我使用了jackson liberary进行JSON解析。
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
val objectMapper = new ObjectMapper() with ScalaObjectMapper
objectMapper.registerModule(DefaultScalaModule)
val str = "[{\"firstName\":\"Pierre\",\"age\":\"20\",\"timestamp\":\"123\"},{\"firstName\":\"Jack\",\"age\":\"20\",\"timestamp\":\"123\"},{\"firstName\":\"Olive\",\"age\":\"20\",\"timestamp\":\"123\"},{\"firstName\":\"Tom\",\"age\":\"20\",\"timestamp\":\"123\"}]"
//convert JSON string to Map(String,String)
val jsonMap = objectMapper.readValue(str, classOf[Array[Map[String, String]]])
//Overwrite the key time-stamp in the given Map
val changedMap = jsonMap.map(_ ++ Map("timestamp" -> "466"))
//Convert the Map again to string
val jsonString = objectMapper.writeValueAsString(changedMap)
println(jsonString)
//output
//[{"firstName":"Pierre","age":"20","timestamp":"466"},{"firstName":"Jack","age":"20","timestamp":"466"},{"firstName":"Olive","age":"20","timestamp":"466"},{"firstName":"Tom","age":"20","timestamp":"466"}]