gpt4 book ai didi

java - 如何使用 String 类型的变量创建 JSON 文件

转载 作者:行者123 更新时间:2023-12-01 21:27:39 25 4
gpt4 key购买 nike

我有一个 String 类型的变量,我需要使用该变量创建一个 json 文件。

我需要创建包含变量“结果”内容的JSON文件

希望您能帮助我!

提前致谢!

@TargetApi(Build.VERSION_CODES.KITKAT)
public String showResult(View v) throws IOException {

String result = "";

Gson json = new Gson();
for (Planet p : plAdapter.getBox()) {
if (p.isSelected()){
/*json.put("name",p.getName());
json.put("distance",p.getDistance());
json.put("quantity",p.getQuantità());*/
result=result+json.toJson(p);


}
}
//result=json.toString();

String path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/droidText/";

//FileWriter file=null;

/* try {
file = new FileWriter(path+"filename5.json");
file.write(result);


}catch(IOException ie){}
finally{


file.flush();
file.close();
}*/try(FileWriter file = new FileWriter(path + "filename.json")) {
// file=new FileWriter(path+"filename100.json");
/*FileWriter file = new FileWriter(path+"filename31.json");
file.write(result);
file.close();
*/
json.toJson(result);
//System.out.println("Successfully wrote Json result to file.");
/*catch(IOException r){

}*/
}catch (IOException e){

}
System.out.println(result);
return result;

}

最佳答案

public static String showResult(View v) {
String result = "";
JsonObject json = new JsonObject():
for (Planet p : plAdapter.getBox()) {
if (p.isSelected()){
json.put("name",p.getName());
json.put("distance",p.getDistance());
json.put("quantity",p.getQuantità());
}
}
result = json.toString();
FileWriter file = null;
try {
file = new FileWriter("/path/filename.json");
file.write(result);
}catch(IOException ie){}
finally{
file.flush();
file.close();
}
return result;
}

关于java - 如何使用 String 类型的变量创建 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37828919/

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