在 java 中将带有嵌套字符的字符串转换为特定的类似 json 的格式



有一个字符串,如下所示:

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;
}

最新更新