我是使用 Java 将 JSON 写入文件的新手。我要求以以下格式发送,需要用 Java 编写。
{
Name : "sam",
"Id":"1234",
"Values": {
"Car":"Maruti"
},
"Price":"100000"
}
请帮忙。
导入json.org并尝试这个:
JSONObject json = new JSONObject(); //creates main json
json.put("Name", "sam");
json.put("Id", 1234);
JSONObject valuesJson = new JSONObject(); //another object
valuesJson.put("Car", "Maruti");
json.put("Values", valuesJson); //puts a json inside another
String jsonString = json.toString();
//next, saves the file:
PrintWriter out1 = null;
try {
out1 = new PrintWriter(new FileWriter("C:\\Users\\YOURNAME\\Documents\\json.txt"));
out1.write(jsonString);
} catch (Exception ex) {
System.out.println("error: " + ex.toString());
}
不要忘记正确设置文件路径!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句