ObjectOutputStream.writeUTF 在开头写入损坏的字符

ObjectOutputStream.writeUTF writes corrupt characters at the start

这是我的 .json 文件:

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

(我尽量在评论中将我的代码从西班牙语翻译成英语 <3)

写在JSON里的函数是这个:

 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);
    }

所以,如果在我的 "create user" JFrame window 中,我创建了一个新用户 "asdf" 作为所有用户详细信息中的信息,我应该得到以下 JSON 文件:

{"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"}]}

是的!那个会发生!但如果我的 JSON 主要对象,我也会在前面看到一些奇怪的 ascii/Unicode 符号。我不能在这里复制输出,所以这是我在 imgur 上的输出:link.

为什么会出现这个问题?我该如何解决? 如果有人需要我的 json 文件 reader(也许问题就在那里),给你:

    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));
 }

所以,在写入 JSON 文件后,我无法用它做任何事情,因为使用这些奇怪的符号,我的 json 中出现错误:"extraneus input: (here are the symbols) expecting [STRING, NUMBER, TRUE, FALSE, {..."

writeUTF 不编写标准的 unicode,而是在输出前加上两个字节的长度信息

如果故意用writeUTF,就得用readUTF重新读取数据。否则我建议使用 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.


** 编辑以澄清 OutputStreamWriter:

要使用 OutputStreamWriter,只需将 ObjectOutputStream 替换为 OutputStreamWriter,并使用 write 而不是 writeUTF

您可能会发现这个小教程很有帮助:Java IO: OutputStreamWriter on jenkov.com