Home  >  Article  >  Java  >  Java reads json data and solves Chinese garbled characters

Java reads json data and solves Chinese garbled characters

尚
Original
2019-12-02 09:14:234486browse

Java reads json data and solves Chinese garbled characters

Java code that reads json data and appears garbled: (Recommended: java video tutorial)

//从json文件中读取数据
		StringBuffer stringBuffer = new StringBuffer();
		try {
			BufferedReader bufferedReader = 
					new BufferedReader(new InputStreamReader(new FileInputStream(file)));
			String line;
			while((line=bufferedReader.readLine()) != null) {
				stringBuffer.append(line);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//开始解析
		JSONObject jsonObject = new JSONObject(stringBuffer.toString());

Solution

according to According to the online description, the file is set to UTF-8 encoding, but if it is saved as a UTF-8 encoded file, there will be 3 more bytes of data identifying the encoding type in the file header, causing the JSONObject object to fail to be parsed. The reason: it is not { beginning.

Idea: We open it by editing, and the UTF-8 encoding format is displayed normally. Then we use the binary editing tool to delete the UTF-8 identifier EF BB BF in the file header, and then in the code, use InputStreamReader to let the data flow from UTF-8 encoding is used in the process of converting byte stream to character stream

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));

For more java knowledge, please pay attention to the java basic tutorial column.

The above is the detailed content of Java reads json data and solves Chinese garbled characters. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn