HarmonyOS 读取本地json文件转成字符串

我有一个省市的城市json文件,我要在项目中使用这个json文件

问题一:我要将这个文件放到哪个文件夹下边?

问题二: 在项目中怎么读取这个文件并且转成字符串 ,进行使用

HarmonyOS
2024-12-26 13:48:28
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
superinsect

需要把json文件存放在rawfile中,然后再ets中编写demo,如下:(仅供参考)

import { BusinessError } from '@ohos.base';

import { Context } from '@ohos.abilityAccessCtrl';
import buffer from '@ohos.buffer';
@Entry
@Component
struct Index2 {
  @State message: string = 'Hello World';
  private context: Context = getContext(this);
  aboutToAppear(): void {
    try {
      this.context.resourceManager.getRawFileContent("city.json", (error: BusinessError, value: Uint8Array) => {
        if (error != null) {
          console.error("error is ===" + error);
        } else {
          let rawFile = value;
          let str : String = buffer.from(value.buffer).toString();
          console.info(json string is ===-> ${str})
        }
      });
    } catch (error) {
      let code = (error as BusinessError).code;
      let message = (error as BusinessError).message;
      console.error(callback getRawFileContent failed, error code:==== ${code}, message: ${message}.);
    }
  }
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
      }
      .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.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
分享
微博
QQ
微信
回复
2024-12-26 16:32:59


相关问题
ResourceStr 类型如何转成字符串
984浏览 • 1回复 待解决
HarmonyOS 超长JSON字符串解析
793浏览 • 2回复 待解决
如何打印JSON对象和JSON字符串
877浏览 • 1回复 待解决
HarmonyOS 如何解析json字符串
1295浏览 • 1回复 待解决
HarmonyOS 在ArkTS中map如何转成字符串
460浏览 • 1回复 待解决
嵌套JSON字符串解析问题
2510浏览 • 1回复 待解决
如何解析JSON字符串
1757浏览 • 1回复 待解决
如何读取本地JSON文件
2733浏览 • 1回复 待解决
HarmonyOS 如何读取本地json文件
705浏览 • 1回复 待解决
如何实现Map转JSON字符串
1655浏览 • 1回复 待解决
HarmonyOS ArkTS如何读取本地json文件
460浏览 • 1回复 待解决
如何将对象转为JSON字符串
1009浏览 • 1回复 待解决
关于鸿蒙arkts解析json字符串问题
1268浏览 • 2回复 待解决