java - 在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"]
解决方案
对于这样一个微不足道的例子,很容易为String
你的内容生成一个格式不正确的 JSON 并让它JSONObject
修补它。
在一个表达式中:
new JSONObject(String.format("{%s}", str.replaceAll("([^,]+),([^,]+)(,|$)", "$1:$2,")))
// {"art":0,"comedy":0,"action":0,"crime":0,"animals":0}
如果你真的想保留0.0
as String
s:
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"
等情况一起使用。
免责声明:这不是疯狂性感的代码,而是放在一行注释中,只要数据结构保持简单,它可能是合理的。
推荐阅读
- reactjs - 材质 UI 从 3 迁移到 4:未捕获的类型错误:无法读取未定义的属性“根”
- python - 如何减小我从 keras 转换的 .tflite 的大小
- javascript - 如何在 Windows 10 和 nodejs 中获取 tmp 文件夹的绝对路径?
- amazon-web-services - 共享 AWS 用户 ARN
- c++ - 如何将所有权从共享指针向量转移到另一个?
- vba - 如何在不使用选择的情况下更改当前段落的格式
- javascript - 复选框切换状态后 ChromeVox 无法读取跨度
- python - NameError:name 'create_model' is not defined ....我已经尝试从 keras 导入模型,但它没有解决它。如何解决?
- flutter - Flutter:如何使用 sharedPreferences 设置 Switch 的状态
- html - 动画取决于屏幕的宽度和高度