作者:牧家三少 | 来源:互联网 | 2024-12-01 14:37
我在尝试编写一个.JSON文件,并希望能在Android应用中读取它。然而,当我试图将整个文件作为一个字符串读取时,遇到了一个问题:每个字符前后都多出了空格,这导致了JSON解析失败。
例如,JSON格式应该是这样的:
[{"description1":"The Thinker - A bronze sculpture by Auguste Rodin. It depicts a man in deep meditation, struggling with intense inner turmoil.","description2":"Steve Jobs - Founder of Apple, widely acknowledged as a key figure in the personal computer revolution.","description3":"Justin Bieber - Born in 1994, a prominent figure in the music industry, winning multiple awards in recent years."}]
但是,实际读取的结果却变成了:
[ { " d e s c r i p t i o n 1 " : " T h e ...
为了去除这些多余的空格,我已经尝试了一些方法,比如使用Java中的字符串操作来替换多个空格为单个空格以及删除前导空格,但都没有解决问题。
目前使用的读取代码如下:
File folderPath = Environment.getExternalStorageDirectory();
File filePath = new File(folderPath, "description.json");
StringBuffer fileData = new StringBuffer(1000);
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(filePath));
char[] buffer = new char[1024];
int numRead;
while ((numRead = reader.read(buffer)) != -1) {
String readData = String.valueOf(buffer, 0, numRead);
fileData.append(readData);
buffer = new char[1024];
}
} finally {
if (reader != null) reader.close();
}
String respOnse= fileData.toString();
尽管如此,“response”字符串仍然包含了异常的空格。
因此,如果有人能提供帮助,将不胜感激。
此外,我在写入文件时使用了以下代码:
FileOutputStream fos = new FileOutputStream(filePath);
DataOutputStream dos = new DataOutputStream(fos);
dos.writeChars(response);
然而,这种方法似乎并不适合处理JSON数据的写入。