[英]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.