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

标签 java utf-8 java-io

这是我的 .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);
    }

因此,如果在我的“创建用户”JFrame 窗口中,我创建一个新用户,并在所有用户详细信息中使用“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 文件阅读器(也许问题就在那里),你可以:

    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 输入:(这里是符号)期望 [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

关于java - ObjectOutputStream.writeUTF 在开头写入损坏的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54066518/

相关文章:

ROracle 连接并拉取 utf8 字符

html - 如何在 MySQL 中转换 HTML 字符引用?

java - 试用资源关闭订单

java - 如何删除 cardview 中不必要的顶部填充?

java - 运行 Solr 需要有效的 Java 8 吗?

java - Android fft 获得更高的频率范围

java - 如何使用java代码与系统命令行交互

java - 更新 MutableLiveData 时可观察到的抛出异常

ruby-on-rails - Rails、IE、PostgreSQL、delayed_job 的奇怪 UTF-8 字节编码问题

java - 我如何在 Java 中压缩文件而不包含文件路径