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

AWS*_*per 2 java string json

我无法格式化以下字符串:

"Sony,20,30,40;LG,1,4,8"
Run Code Online (Sandbox Code Playgroud)

以下 JSON 格式:

"reported": {
    "SETS": [
      {
        "prodName": "Sony",
        "fmtd": "20",
        "lmtd": "30",
        "lm": "40"
      },
      {
        "prodName": "LG",
        "mtd": "1",
        "lmtd": "4",
        "lm": "8"
      }
    ]
  }
Run Code Online (Sandbox Code Playgroud)

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是得到这种格式:

{"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"},]}
Run Code Online (Sandbox Code Playgroud)

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

Pav*_*ngh 5

只需删除内部循环

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);
Run Code Online (Sandbox Code Playgroud)

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