there is such a json, it is in the settings.json file

{ "settings" : { "pathDownloads" : "", "pathFolder" : { "archive" : "", "music" : "", "android" : "", "web" : "", "images" : "" } } } 

It is necessary to read it in jsonObject, well, and there to change, add a new one and write the modified json back to the file.
The problem itself: read and write json file revised many examples, m. is there any library?

    2 answers 2

    Standard library org.json

    JSON.simple

    GSON

    Jackson

       import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Iterator; public class Main { public static void main(String[] args) { JSONObject object = new JSONObject(); object.put("name", "mkyong.com"); object.put("age", new Integer(100)); JSONArray list = new JSONArray(); list.add("msg 1"); list.add("msg 2"); list.add("msg 3"); object.put("messages", list); try{ FileWriter file = new FileWriter("test.json"); file.write(object.toJSONString()); file.flush(); file.close(); } catch (IOException ex){ ex.printStackTrace(); } //============================================ // остановить перед чтением файла JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader("test.json")); JSONObject jsonObject = (JSONObject) obj; String name = (String) jsonObject.get("name"); System.out.println(name); long age = (Long) jsonObject.get("age"); System.out.println(age); // loop array JSONArray msg = (JSONArray) jsonObject.get("messages"); Iterator<String> iterator = msg.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } } 
      • The answer seems to be normal, restored. - Nick Volynkin
      • Please try to write more detailed answers. I am sure the author of the question would be grateful for your expert commentary on the code above. - Nicolas Chabanovsky