需求是這樣的:
- 嗯,我想把JSON數據從文件中讀取出來,讀取為字符串,然后傳到前端展示。
遇到的問題是這樣的:
- 把JSON文件解析為字符串
- 把字符串傳到前端在展示為JSON格式。
我是這樣解決的:
- 使用IO流的知識,轉換為字符串
- 使用vue-json-viewer插件展示讀取的數據

JSON文件轉字符串:
import com.liruilong.demotext.service.utils.interfaceutils.InputStreamPeocess; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; /** * @Description : * @Author: Liruilong * @Date: 2020/3/15 18:37 */ public class EncodingUtil { final static Logger logger = LoggerFactory.getLogger(EncodingUtil.class); /** * @return java.lang.String * @Author Liruilong * @Description 文件轉字符串 * @Date 17:22 2020/3/17 * @Param [file] **/ public static String readJsonToString(File file) { String string = null; if (!file.exists() || file.isDirectory()) { System.out.println("輸入路徑不對"); } else { try { string = fileToBufferedReader((bufferedReader) -> { String str = null; StringBuilder stringBuilder = new StringBuilder(); while ((str = bufferedReader.readLine()) != null) { stringBuilder.append(str); } return stringBuilder.toString(); }, file); } catch (IOException e) { e.printStackTrace(); } } return string; } /** * @return java.lang.String * @Author Liruilong * @Description 環繞處理 * @Date 17:14 2020/3/17 * @Param [inputStreamPeocess, file] **/ public static String fileToBufferedReader(InputStreamPeocess inputStreamPeocess, File file) throws IOException { try (FileInputStream fileInputStream = new FileInputStream(file)) { try (InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream)) { try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) { return inputStreamPeocess.peocess(bufferedReader); } } } } }
package com.liruilong.demotext.service.utils.interfaceutils; import java.io.BufferedReader; import java.io.IOException; /** * @Description : 函數接口,描述BufferedReader ->String的轉化方式 * @Author: Liruilong * @Date: 2020/3/17 15:44 */ @FunctionalInterface public interface InputStreamPeocess { /** * @Author Liruilong * @Description 方法簽名 BufferedReader ->String * @Date 15:47 2020/3/17 * @Param [inputStream] * @return com.liruilong.demotext.service.utils.InputStream **/ String peocess(BufferedReader bufferedReader) throws IOException; }
前端Vue處理: :value放字符串
<json-viewer :value="showtext" :expand-depth=4 copyable sort></json-viewer>
vue-json-viewer教程:
官方: https://www.npmjs.com/package/vue-json-viewer
安裝:
$ npm install vue-json-viewer --save
引用:
import JsonViewer from 'vue-json-viewer'Vue.use(JsonViewer)
使用
<json-viewer :value="showtext" :expand-depth=4 copyable sort></json-viewer>
參數:
| Property | Description | Default |
|---|---|---|
value |
JSON data (can be used with v-model) |
Required |
expand-depth |
Collapse blocs under this depth | 1 |
copyable |
Display the copy button, you can customize copy text just set {copyText: 'copy', copiedText: 'copied'} or set true use default copytext |
false |
sort |
Sort keys before displaying | false |
boxed |
Add a fancy "boxed" style to component | false |
theme |
Add a custom CSS class for theming purposes | jv-light |
