2

this is my .json file:

{"Usuarios":[{"password":"admin","apellido":"Admin","correo":"Adminadmin.com","direccion":"Admin","telefono":"Admin","nombre":"Admin","username":"admin"}]}

(I tried to translate my code from Spanish to English in the comments as best I could <3)

The function that writes in the JSON is this one:

 public void agregarUsuario(String nombre, String apellido, String direccion, String telefono, String correo, String username, String password) {
    try {
        //String jsonString = JsonObject.toString();

        JSONObject usuarios = getJSONObjectFromFile("/usuarios.json"); 
        JSONArray listaUsuario = usuarios.getJSONArray("Usuarios");     
        JSONObject newObject = new JSONObject();                        
        newObject.put("nombre", nombre);
        newObject.put("apellido", apellido);
        newObject.put("direccion", direccion);
        newObject.put("telefono", telefono);
        newObject.put("correo", correo);
        newObject.put("username",username);
        newObject.put("password", password);

        listaUsuario.put(newObject);                                    
        usuarios.put("Usuarios",listaUsuario);  

        ObjectOutputStream outputStream = null;

        outputStream = new ObjectOutputStream(new FileOutputStream("C:\\Users\\Victor\\eclipse-workspace\\Iplane\\assets\\usuarios.json"));

        outputStream.writeUTF(usuarios.toString());
        outputStream.flush();
        outputStream.close();

    }catch(JSONException e) {
        e.printStackTrace();
    }catch(Exception e) {
        System.err.println("Error writting json: " + e);
    }

So, if in my "create user" JFrame window ,I create a new user with "asdf" as info within all the user's details, I should get the following JSON file:

{"Usuarios":[{"password":"admin","apellido":"Admin","correo":"Adminadmin.com","direccion":"Admin","telefono":"Admin","nombre":"Admin","username":"admin"},{"password":"asdf","apellido":"asdf","correo":"asdf","direccion":"asdf","telefono":"asdf","nombre":"asdf","username":"asdf"}]}

And yes! that happens! but I got also, some weird ascii/Unicode symbols in front if my JSON main object. I cant copy the output here, so this is my output on imgur: link.

Why this problem happens? how could I fix it? If someone need my json file reader (maybe the problem is there) here you go:

    public static InputStream inputStreamFromFile(String path) {
    try {
        InputStream inputStream = FileHandle.class.getResourceAsStream(path); //charge json in "InputStream"
        return inputStream;
    }catch(Exception e) {
        e.printStackTrace(); //tracer for json exceptions
    }
    return null;
}
 public static String getJsonStringFromFile(String path) {
        Scanner scanner;
        InputStream in = inputStreamFromFile(path); //obtains the content of the .JSON and saves it in: "in" variable
        scanner = new Scanner(in);                              //new scanner with inputStream "in" info
        String json= scanner.useDelimiter("\\Z").next();        //reads .JSON and saves it in string "json"
        scanner.close();                                        //close the scanner
        return json;                                            //return json String
     }
 public static boolean objectExists (JSONObject jsonObject, String key) { //verifies whether an object exist in the json
     Object o;
     try {
         o=jsonObject.get(key);
     }catch(Exception e) {
         return false;
     }
     return o!=null;
 }

  public static JSONObject getJSONObjectFromFile(String path) {    //creates a jsonObject from a path
     return new JSONObject(getJsonStringFromFile(path));
 }

So, after writing in JSON file, I cant do anything with it, because with this weird symbols, I got errors in my json: "extraneus input: (here are the symbols) expecting [STRING, NUMBER, TRUE, FALSE, {..."

Raedwald
  • 46,613
  • 43
  • 151
  • 237
Mamey
  • 81
  • 1
  • 10
  • ObjectOutputStream is not for writing text or JSON. The writeUTF method does not write true UTF-8 text. Use an [OutputStreamWriter](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/OutputStreamWriter.html) instead. – VGR Jan 06 '19 at 23:06
  • Hi & welcome to StackOverflow. If you have not yet, please check out [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) in the Help Center. To make this question a great question you could have tried if the output is funny with any String or only with the JSON you tried, and a [minimal example](https://stackoverflow.com/help/mcve) would have worked without all the JSON which distracts from the real problem (the wrong OutputStream writer beeing chosen). Please consider reworking your question so others with similar problems will learn/find their solution quicker :) – Yolgie Jan 07 '19 at 00:19
  • If you have questions or need help, I will hang out in a chat room I created for you for some time: https://chat.stackoverflow.com/rooms/186278/question-stranges-ascii-unicode-characters-while-wriiting-in-a-json-file – Yolgie Jan 07 '19 at 00:23

1 Answers1

2

writeUTF does not write standard unicode but prepends the output with two bytes of length information

If you use writeUTF intentionally, you have to use readUTF to read the data again. Otherwise I would suggest using an OutputStreamWriter.

writeUTF()

Writes two bytes of length information to the output stream, followed by the modified UTF-8 representation of every character in the string s. If s is null, a NullPointerException is thrown. Each character in the string s is converted to a group of one, two, or three bytes, depending on the value of the character.


** Edit to clarify OutputStreamWriter:

To use the OutputStreamWriter just replace the ObjectOutputStream with OutputStreamWriter and use write instead of writeUTF.

You might find this small tutorial helpfull: Java IO: OutputStreamWriter on jenkov.com

Yolgie
  • 268
  • 3
  • 16
  • See also: [Stackoverflow: Whats the difference between `writeUTF` and `writeChars`](https://stackoverflow.com/questions/18945202/whats-the-difference-between-writeutf-and-writechars) – Yolgie Jan 06 '19 at 23:12
  • how can I use an OutputStreamWriter in my code? Im student im really new on json stuff – Mamey Jan 07 '19 at 00:01