如何获取工程目录下的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%') 
  } 
}
  • 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.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.

参考链接

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

分享
微博
QQ
微信
回复
2024-05-31 21:13:07
相关问题
鸿蒙如何读取resources目录下文件
4501浏览 • 1回复 待解决
HarmonyOS 工程目录下ohosTest调试问题
1184浏览 • 1回复 待解决
java怎么读取公共目录下文件
3149浏览 • 1回复 待解决