import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class JSonSampl2 {
private static void readJSON() {
try {
File file = new File("./notes.json");
String content = FileUtils.readFileToString(file, "utf-8");
JSONObject person = new JSONObject(content);
System.out.println(person.toString(4));
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
private static void createJSON(boolean prettyPrint) {
JSONObject person = new JSONObject();
person.put("name", "Вася");
person.put("birthday", "1980-02-10");
person.put("age", 40);
person.put("married", false);
person.put("car", JSONObject.NULL);
person.put("favorite_foods", new String[] { "мясо", "рыба", "фрукты" });
JSONObject passportJsonObj = new JSONObject();
passportJsonObj.put("id", 100001);
person.put("passport", passportJsonObj);
try(BufferedWriter bw = new BufferedWriter(new FileWriter("notes.json")))
{
if (prettyPrint) {
bw.write(person.toString(4));
} else {
bw.write(person.toString());
}
}
catch(IOException ex){
System.out.println(ex.getMessage());
}
}
public static void main(String[] args) {
createJSON(true);
readJSON();
}
}