首页 > 解决方案 > 在java中将逗号分隔的字符串转换为json

问题描述

我有一个逗号分隔的字符串,需要转换为 JSON 字符串,当我进行 JSONArray 转换时,它仍然是数组格式。解决此问题的最佳方法是什么。

String str="art,0.0, comedy,0.0, action,0.0, crime,0.0, animals,0.0"

预期产出

{"art":"0.0", "comedy":"0.0","action":"0.0","crime":"0.0","animals":"0.0"}

这是我尝试过的代码

String [] arrayStr=strVal.split(",");
JSONArray mJSONArray = new JSONArray();
for (String s: arrayStr){
    mJSONArray.put(s);
}
System.out.println(mJSONArray.toString());

输出

["art","0.0"," comedy","0.0"," action","0.0"," crime","0.0"," animals","0.0"]

标签: javastringjava-8

解决方案


对于这样一个微不足道的例子,很容易为String你的内容生成一个格式不正确的 JSON 并让它JSONObject修补它。

在一个表达式中:

new JSONObject(String.format("{%s}", str.replaceAll("([^,]+),([^,]+)(,|$)", "$1:$2,")))
// {"art":0,"comedy":0,"action":0,"crime":0,"animals":0}

如果你真的想保留0.0as Strings:

new JSONObject(String.format("{%s}", str.replaceAll("([^,]+),([^,]+)(,|$)", "$1:\"$2\",")))
// {"art":"0.0","comedy":"0.0","action":"0.0","crime":"0.0","animals":"0.0"}

如果您想考虑可能的无关空格:

new JSONObject(String.format("{%s}", str.replaceAll("([^,]+)\\s*?,\\s*?([^,]+)(,|$)", "$1:$2,")))

.. 将与输入"art, 0.0, comedy, 0.0, action, 0.0, crime, 0.0, animals, 0.0"等情况一起使用。


免责声明:这不是疯狂性感的代码,而是放在一行注释中,只要数据结构保持简单,它可能是合理的。


推荐阅读