gpt4 book ai didi

java - 解析字符串并创建 json 格式,然后保存到文本文件

转载 作者:行者123 更新时间:2023-12-01 18:09:00 24 4
gpt4 key购买 nike

我想创建一个 json 文本并将其保存到文本文件中。这是到目前为止我编辑过的代码。我希望 jsonFormat.txt 中的输出必须包含这些字符串 {"Fname": "John low","Mname":"Bajud", "Lname": "Saddy"}。

        File myFile = new File("/sdcard/jsonFormat.txt");
myFile.createNewFile();
String delim = "\\|";
String[] temp;
String temp2;
String data ="|Fname:John low|Mname:Bajud|Lname:Saddy|";

data = data.substring(1, data.length() - 1);
temp2 = data.split(delim);

JSONObject jsonObject = new JSONObject();

for(int index=0;index < temp2.length() ;index++){
String[] sub_temp2 = temp2[index].split(":");
jsonObject.put(sub_temp2[0],sub_temp2[1]);
}

FileOutputStream fOuts = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOuts);
myOutWriter.append(jsonObject.toString());
myOutWriter.close();
fOuts.close();

我决定解决我的问题,经过一番挣扎,我想出了一个解决方案:)这是我对上述问题的解决方案:)

 try {
File myFile = new File("/sdcard/jsonFormat.txt");
FileOutputStream fOuts = new FileOutputStream(myFile);
myFile.createNewFile();

StringBuilder builder = new StringBuilder();
StringBuilder builder2 = new StringBuilder();
String delim = "\\|";
String delim2 = "\\:";
String[] temp;
String[] temp2;
String[] sub;
String data = "|Fname:James Bryan|Mname:Baguio|Lname:Juventud|Age:21|Gender:Male|Fname:James Bryan|Mname:Baguio|Lname:Juventud|Age:21|Gender:Male|";

data = data.substring(1, data.length() - 1);
temp2 = data.split(delim);
//System.out.print(temp2[1]+"\n"); = Fname:James Bryan
builder.append("{");

int k=1;
for(int i=0;i<temp2.length;i++){
//System.out.print(temp2[i]+"\n");
sub = temp2[i].split(delim2);
for(int x=0;x<sub.length;x++){
builder.append("\"");
builder.append(sub[x]);
builder.append("\"");

if(k<2){
builder.append(":");
k++;
}
else
k--;
}
builder.append(",");
}
builder.append("}");

String newData = builder.substring(0, builder.length()-2);
builder2.append(newData);
builder2.append("}");
//System.out.println(builder2.toString());
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOuts);
myOutWriter.append(builder2);
myOutWriter.close();
fOuts.close();

} catch (Exception e) {
e.printStackTrace();

}

输出:JSON 字符串文本文件

 {"Fname": "James Bryan","Mname": "Baguio","Lname": "Juventud","Age": "21","Gender": "Male","Fname": "James Bryan","Mname": "Baguio","Lname": "Juventud","Age": "21","Gender": "Male"}

最佳答案

你的代码

temp2 = data.split(delim);

不会工作,因为你的delim是错误的

尝试

String delim = "\\|";

temp2应该是一个字符串数组;

关于java - 解析字符串并创建 json 格式,然后保存到文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34303705/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com