【HarmonyOS】如何读取Raw下的JSON文件内容
【HarmonyOS】如何读取Raw下的JSON文件内容
一、问题背景:
读取工程中/resources下json文件,json文件推荐放在rawfile路径下,通过getRawFileContent接口访问。但是通过该接口拿到的是Uint8Array类型数据,那怎么拿到JSON的文本内容?
二、解决方案:
1.首先通过getRawFileContent拿到文件的字节流内容。
getContext().resourceManager.getRawFileContent("vibration.json")
2.通过util.TextDecoder设置编码,解析字节流内容转化为string文本。
import { util, buffer } from '@kit.ArkTS';
let decoder = util.TextDecoder.create('utf-8');
let json = decoder.decodeToString(rawFile);
三、源码示例:
JSONTestPage.ets
import { BusinessError } from '@kit.BasicServicesKit';
import { util, buffer } from '@kit.ArkTS';
struct JSONTestPage {
private TAG: string = "JSONTestPage";
showText: string = "";
aboutToAppear(): void {
this.getRawJson();
}
/**
* 获取JSON
*/
private getRawJson(){
try {
getContext().resourceManager.getRawFileContent("vibration.json").then((value: Uint8Array) => {
let rawFile = value;
let decoder = util.TextDecoder.create('utf-8');
let json = decoder.decodeToString(rawFile);
console.info(this.TAG, "json: " + json);
this.showText = json;
}).catch((error: BusinessError) => {
console.error("getRawFileContent promise error is " + error);
});
} catch (error) {
let code = (error as BusinessError).code;
let message = (error as BusinessError).message;
console.error(`promise getRawFileContent failed, error code: ${code}, message: ${message}.`);
}
}
build() {
Scroll(){
Row() {
Text(this.showText)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
}
.height('100%')
.width('100%')
}
}
vibration.json
{
"MetaData": {
"Create": "2023-01-09",
"Description": "a haptic case",
"Version": 1.0,
"ChannelNumber": 1
},
"Channels": [
{
"Parameters": {
"Index": 0
},
"Pattern": [
{
"Event": {
"Type": "transient",
"StartTime": 0,
"Parameters": {
"Frequency": 31,
"Intensity": 100
}
}
},
{
"Event": {
"Type": "continuous",
"StartTime": 40,
"Duration": 54,
"Parameters": {
"Frequency": 30,
"Intensity": 38,
"Curve": [
{
"Time": 0,
"Frequency": 0,
"Intensity": 0
},
{
"Time": 1,
"Frequency": 15,
"Intensity": 0.5
},
{
"Time": 40,
"Frequency": -8,
"Intensity": 1.0
},
{
"Time": 54,
"Frequency": 0,
"Intensity": 0
}
]
}
}
}
]
}
]
}