[英]Convert string with nested characters into specific json like format in java
有一個像這樣的字符串:
String query = "param1, param2, param3{npam1, npam2, npam3{nipam1, nipam2}}";
此字符串需要按以下格式處理:
{
param1: param1,
param2: param2,
param3: {
npam1: param3.npam1,
npam2: param3.npam2,
npam3: {
nipam1: param3.npam3.nipam1,
nipam2: param3.npam3.nipam2
}
}
}
已經完成了 2 個嵌套,但重點是要查詢的字符串可以擴展到任意數量的嵌套卷曲。
我所做的是遍歷字符串中的對象,然后遍歷每個對象的屬性。 希望它能幫助你解決你的問題。 同樣在您的初始字符串中,您缺少左括號和右括號,因此我添加了它們。
String jsonWithOutFormat = "param1, param2, param3{npam1, npam2, npam3{nipam1, nipam2}}";
jsonWithOutFormat = jsonWithOutFormat.replaceAll(" ", "");
String json = "";
String[] objectsInString = jsonWithOutFormat.split("[{]");
List<String> nestedObjects = new ArrayList<>();
json += "{";
for (int i = 0; i < objectsInString.length; i++) {
String[] objectAttributes = objectsInString[i].split("[,]");
if(i==0)
nestedObjects.add(objectAttributes[objectAttributes.length-1] + ".");
else
nestedObjects.add(nestedObjects.get(i-1)+objectAttributes[objectAttributes.length-1] + ".");
for (int j = 0; j < objectAttributes.length; j++) {
if(!(j == objectAttributes.length-1)) {
if(i != 0)
json+= objectAttributes[j] + ": " + nestedObjects.get(i-1) + objectAttributes[j] + ", ";
else
json+= objectAttributes[j] + "\"" + ": " + "\"" + objectAttributes[j] + "\"" + ", ";
}
else {
if(!(i == objectsInString.length-1))
json+= objectAttributes[j] + ": {";
else {
json+= objectAttributes[j].replaceAll("}", "") + ": " + nestedObjects.get(i-1) + objectAttributes[j];
}
}
}
}
json += "}";
System.out.print("\n" + json);
}
謝謝喬治。 通過傳遞實際的字符串(未格式化的字符串),可以調用此方法以生成所需格式的 json。
public String expressionConstruct(String jsonWithOutFormat) {
jsonWithOutFormat = jsonWithOutFormat.replaceAll(" ", "");
String json = "";
String[] objectsInString = jsonWithOutFormat.split("[{]");
List<String> nestedObjects = new ArrayList<>();
json += "{";
for (int i = 0; i < objectsInString.length; i++) {
String[] objectAttributes = objectsInString[i].split("[,]");
if(i==0)
nestedObjects.add(objectAttributes[objectAttributes.length-1] + ".");
else
nestedObjects.add(nestedObjects.get(i-1)+objectAttributes[objectAttributes.length-1] + ".");
for (int j = 0; j < objectAttributes.length; j++) {
if(!(j == objectAttributes.length-1)) {
if(i != 0)
json+= objectAttributes[j].replaceAll("}", "") + ": " + nestedObjects.get(i-1) + objectAttributes[j] + ", ";
else
json+= objectAttributes[j] + ": " + objectAttributes[j] + ", ";
}
else {
if(!(i == objectsInString.length-1))
json+= objectAttributes[j] + ": {";
else {
json+= objectAttributes[j].replaceAll("}", "") + ": " + nestedObjects.get(i-1) + objectAttributes[j];
}
}
}
}
json += "}";
return json;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.