如何获取工程目录下的json文件?

如何获取工程目录下的json文件?

HarmonyOS
2024-05-30 21:49:30
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
QW_MA

开发者你好,同步和异步获取json文件内容的样例代

示例代码

import { Context } from '@ohos.abilityAccessCtrl'; 
import buffer from '@ohos.buffer'; 
 
@Entry 
@Component 
struct Index { 
  private context: Context = getContext(this); 
  private str:string  getRawFile(): ESObject { 
  //调用getRawFileContent接口获取json文件内容,并读为string  
  getContext(this).resourceManager.getRawFileContent("test.json", (err, data) => { 
    try { 
      this.str = buffer.from(data.buffer).toString(); 
    } catch (e) { 
      console.info(JSON.stringify(e)) 
    } 
  }) 
  //也可以调用getRawFileContentSync接口获取json文件内容,并读为string  
  try { 
    let data: Uint8Array = this.context.resourceManager.getRawFileContentSync("test.json"); 
    this.str = buffer.from(data.buffer).toString(); 
  } catch (e) { 
    console.info(JSON.stringify(e)) 
  } 
  // string转为ESObject  
  let obj: ESObject = JSON.parse(this.str) 
  return obj 
} 
 
  build() { 
    Column() { 
      Button("get").onClick(() => { 
        this.getRawFile() 
      }) 
    }.width('100%') 
  } 
}

参考链接

如何读取rawfile中的xml文件并转化为String类型

分享
微博
QQ
微信
回复
2024-05-31 21:13:07
相关问题
鸿蒙如何读取resources目录下文件
1753浏览 • 1回复 待解决
java怎么读取公共目录下文件
1051浏览 • 1回复 待解决
如何动态访问media目录下资源
680浏览 • 1回复 待解决
资源目录下文件到沙箱单向流动
403浏览 • 1回复 待解决
Native侧如何获取可操作文件目录
645浏览 • 1回复 待解决
canvas怎么绘制资源目录下图片
189浏览 • 1回复 待解决
如何监听文件文件目录变化
507浏览 • 1回复 待解决
如何读取本地JSON文件
439浏览 • 1回复 待解决
js api 如何读取预置json文件
5660浏览 • 1回复 待解决