How to get list of json strings from sinlgle line multi json string in scala

时间:2017-12-08 15:37:33

标签: json string scala

I am trying to get list of json string from given string having multiple json strings separated by ",".

For example val jsonString = "{\"a\":\"b\"},{\"c\":\"d\", \"e\":\"f\"}"

expected result , List[String] :
["{\"a\":\"b\"}", "{\"c\":\"d\", \"e\":\"f\"}"]

2 个答案:

答案 0 :(得分:0)

您应该将json分隔符替换为整个字符串中不重复的stringcharacter,并使用该特殊分隔符与split方法一起使用,以获得所需的输出。在这里,我使用了-

jsonString.replace("},{", "}-{").split("-")

您应该输出

res0: Array[String] = Array({"a":"b"}, {"c":"d", "e":"f"})

更进一步,调用toList方法可以获得您需要的最终 dataType

jsonString.replace("},{", "}-{").split("-").toList  //res0: List[String] = List({"a":"b"}, {"c":"d", "e":"f"})

答案 1 :(得分:0)

得到解决方案。

val jsonString = "{\"a\":\"b\"},{\"c\":\"d\", \"e\":\"f\"}"
val jsonListString = "[" + jsonString + "]"
val jsonArray = new JSONArray(jsonListString)

这将创建json数组。