如何将逗号和分号分隔的字符串拆分为JSON对象

时间:2017-08-03 17:01:46

标签: java json string

我无法在字符串下面格式化:

"Sony,20,30,40;LG,1,4,8"

以下JSON格式:

"reported": {
    "SETS": [
      {
        "prodName": "Sony",
        "fmtd": "20",
        "lmtd": "30",
        "lm": "40"
      },
      {
        "prodName": "LG",
        "mtd": "1",
        "lmtd": "4",
        "lm": "8"
      }
    ]
  }

我尝试了下面的代码,但没有得到正确的结果。

String stringFromProc = "SONY,20,30,40;LG,1,4,8";
String[] array1 =  stringFromProc.split("[\\;]");
JSONObject jsonSubObject = null;
JSONObject jsonFinal = new JSONObject();
JSONArray jsonArrayRET = new JSONArray();

for(int i=0;i<array1.length;i++){
    String []array2 = array1[i].split("[\\,]");
    for(int j=0;j<array2.length;j++){
        System.out.println(array2[j]);
        jsonSubObject = new JSONObject();

        jsonSubObject.put("prodName", array2[0]);
        jsonSubObject.put("mtd", array2[1]);
        jsonSubObject.put("lmtd", array2[2]);
        jsonSubObject.put("lm", array2[3]);
        jsonArrayRET.add(jsonSubObject);
        jsonFinal.put("reported", jsonArrayRET);
    }
}

但是要获得这种格式:

{"SETS":[{"lm":"40","lmtd":"30","mtd":"20","prodName":"MNP"},{"lm":"40","lmtd":"30","mtd":"20","kpiName":"MNP"},{"lm":"40","lmtd":"30","mtd":"20","kpiName":"MNP"},{"lm":"40","lmtd":"30","mtd":"20","kpiName":"MNP"},]}

我知道在分割逗号分隔数组后我正在循环但是无法获得如何分割的正确方法。有人请建议。

2 个答案:

答案 0 :(得分:4)

只需删除内部循环

String stringFromProc = "SONY,20,30,40;LG,1,4,8";
String[] array1 =  stringFromProc.split(";"); // simply use ;
// array1[0] = SONY,20,30,40
// array1[1] = LG,1,4,8

JSONObject jsonSubObject = null;
JSONObject jsonFinal = new JSONObject();
JSONArray jsonArrayRET = new JSONArray();

for(int i=0;i<array1.length;i++){
     String []array2 = array1[i].split(","); // simply use ,
     // create jsonobjects 
     // when i=0 mean for sony and next time i = 1 mean for LG  
     jsonSubObject = new JSONObject();
     jsonSubObject.put("prodName", array2[0]);
     jsonSubObject.put("mtd", array2[1]);
     jsonSubObject.put("lmtd", array2[2]);
     jsonSubObject.put("lm", array2[3]);
     // put every object in array 
     jsonArrayRET.add(jsonSubObject);
   }
     // finally put array in reported jsonobject
     jsonFinal.put("reported", jsonArrayRET);

注意:;,不是特殊的正则表达式字符,因此不需要转义\\而不是长信息只需阅读character class []

答案 1 :(得分:1)

移动 jsonFinal.put("reported", jsonArrayRET);

在第二个循环之外,您正在覆盖报告的对象。

    for(int i=0;i<array1.length;i++){
        String []array2 = array1[i].split("[\\,]");
        for(int j=0;j<array2.length;j++){
            System.out.println(array2[j]);
            jsonSubObject = new JSONObject();
            jsonSubObject.put("prodName", array2[0]);

            jsonSubObject.put("mtd", array2[1]);
            jsonSubObject.put("lmtd", array2[2]);
            jsonSubObject.put("lm", array2[3]);
            jsonArrayRET.add(jsonSubObject);
       }
       jsonFinal.put("reported", jsonArrayRET);
   }