Je ne parviens pas à formater la chaîne ci-dessous:
"Sony,20,30,40;LG,1,4,8"
Au format JSON ci-dessous:
"reported": {
"SETS": [
{
"prodName": "Sony",
"fmtd": "20",
"lmtd": "30",
"lm": "40"
},
{
"prodName": "LG",
"mtd": "1",
"lmtd": "4",
"lm": "8"
}
]
}
J'ai essayé le code ci-dessous mais je n'obtiens pas de résultats corrects.
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);
}
}
Mais obtenir ce format:
{"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"},]}
Je sais que je fais une boucle après avoir divisé le tableau séparé par des virgules, mais je ne parviens pas à obtenir l'approche correcte de la séparation. Quelqu'un s'il vous plaît suggérer.
Retirez simplement la boucle interne
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);
Remarque: ;
et ,
ne sont pas des caractères d'expressions régulières spéciales, aucun échappement \\
n'est donc nécessaire et au lieu d'informations longues, lisez simplement la classe de caractères []
Cet article est collecté sur Internet, veuillez indiquer la source lors de la réimpression.
En cas d'infraction, veuillez [email protected] Supprimer.
laisse moi dire quelques mots