如何读取本地JSON文件

如何读取本地JSON文件

HarmonyOS
2024-05-20 21:54:54
1060浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
zxjiu

HarmonyOS如何读取本地JSON文件,且显示在界面中。

代码实现

1.在rawfile目录下创建如下JSON文件。

{ 
  "region": "CN", 
  "configuration_version": "3.0" 
}
  • 1.
  • 2.
  • 3.
  • 4.

2.使用resourceManager.getRawFileContent获取文件字节数组。

import resourceManager from '@ohos.resourceManager'; 
resourceManager.getRawFileContent("province.json", (error, data) => { 
  if (error != null) { 
    console.log("error is " + error); 
    return 
  } 
  //do something 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

3.进行JSON转换

this.json = String.fromCharCode.apply(null,data)
  • 1.

完整示例

@Entry 
@Component 
struct JsonPage { 
  @State message: string = '读取文件' 
  @State json: string = '' 
  
  build() { 
    Row() { 
      Column() { 
        Button(this.message) 
          .fontSize(30) 
          .fontWeight(FontWeight.Bold) 
          .onClick(()=>{ 
            getContext(this).resourceManager.getRawFileContent("province.json",(err,data)=>{ 
              try { 
                this.json = String.fromCharCode.apply(null,data) 
  
              }catch (e){ 
                console.info('Cktest ' + JSON.stringify(e)) 
              } 
            }) 
          }) 
        TextArea({ text: this.json }) 
          .fontSize(10) 
          .height("90%") 
      } 
      .width('100%') 
    } 
    .height('100%') 
  } 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
分享
微博
QQ
微信
回复
2024-05-22 15:43:15
相关问题
HarmonyOS 如何读取本地json文件
1055浏览 • 1回复 待解决
stageMode下如何读取本地json 文件
4247浏览 • 1回复 待解决
HarmonyOS ArkTS如何读取本地json文件
880浏览 • 1回复 待解决
鸿蒙next 中如何读取本地json文件
259浏览 • 0回复 待解决
读取本地json 文件提示权限拒绝
4115浏览 • 1回复 待解决
ArkTS如何读取本地json
7966浏览 • 1回复 待解决
HarmonyOS 读取本地json文件转成字符串
887浏览 • 1回复 待解决
HarmonyOS 如何读取本地文件流?
804浏览 • 1回复 待解决
HarmonyOS fs读取本地文件
1100浏览 • 1回复 待解决
HarmonyOS 如何读取文件router_map.json
747浏览 • 1回复 待解决
js api 如何读取预置的json文件
8331浏览 • 1回复 待解决
Harmony 如何读取本地视频文件路径?
15739浏览 • 2回复 待解决
HarmonyOS 读取本地RawFile文件失败
1234浏览 • 1回复 待解决
HarmonyOS Rawfile中的json文件读取
970浏览 • 1回复 待解决
HarmonyOS项目中json文件文本读取
1922浏览 • 1回复 待解决
怎么读取本地音频文件列表?
7325浏览 • 1回复 待解决
HarmonyOS 怎么解析本地文件json内容?
896浏览 • 1回复 待解决
如何读取本地/预制数据库?
2095浏览 • 1回复 待解决
HarmonyOS如何读取文件
1400浏览 • 1回复 待解决