在逗号中将逗号分隔的字符串转换为json

时间:2018-06-01 22:27:59

标签: java java-8

我有一个逗号分隔的字符串,需要转换为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"]

3 个答案:

答案 0 :(得分:3)

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

在单个表达式中:

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

如果您真的想将0.0保持为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"等输入和其他案例。

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

答案 1 :(得分:2)

您应该使用Map而不是Array(键/值对列表是Map,而不是Array)。

1种方式:使用JsonObject

String [] arrayStr=strVal.split(",");
JsonObjectBuilder builder = Json.createObjectBuilder()

String key = null;
for (String s: arrayStr){
    if(key == null) {
       key = s;
    } else {
       builder.add(key, s);
       key = null;
    }
}
JsonObject value = builder.build();

2路:使用地图

String [] arrayStr=strVal.split(",");
Map<String,String> map = new HashMap<>();

String key = null;
for (String s: arrayStr){
    if(key == null) {
       key = s;
    } else {
       map.put(key, s);
       key = null;
    }
}

// convert Map to Json using any Json lib (Gson, Jackson and so on)

答案 2 :(得分:0)

看起来你想使用JSONObject而不是JSONArray来获得所需的输出。即只需将项添加到对象 - jsonObject.put(key,value)