HarmonyOS鸿蒙Next中如何读取自定义在resources文件夹里面的json

HarmonyOS鸿蒙Next中如何读取自定义在resources文件夹里面的json 如何读取自定义在resources文件夹里面的json

3 回复
try {
  this.context.resourceManager.getRawFileContent("XXX.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}.`);
}

试试

更多关于HarmonyOS鸿蒙Next中如何读取自定义在resources文件夹里面的json的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS(鸿蒙)Next中,读取自定义在resources文件夹内的JSON文件,可以通过ResourceManagerResourceTable来实现。首先,确保JSON文件放置在resources/rawfile目录下。然后,使用ResourceManagergetRawFileContent方法来读取文件内容。以下是示例代码:

import resourceManager from '@ohos.resourceManager';

async function readJsonFile() {
  try {
    const context = getContext(this) as common.UIAbilityContext;
    const resourceMgr = context.resourceManager;
    const jsonContent = await resourceMgr.getRawFileContent('your_json_file.json');
    const jsonString = String.fromCharCode.apply(null, jsonContent);
    const jsonObject = JSON.parse(jsonString);
    console.log(jsonObject);
  } catch (error) {
    console.error('Failed to read JSON file:', error);
  }
}

在上述代码中,your_json_file.json是放置在resources/rawfile目录下的JSON文件名。getRawFileContent方法返回的是文件的二进制数据,通过String.fromCharCode将其转换为字符串,然后使用JSON.parse解析为JavaScript对象。

在HarmonyOS鸿蒙Next中读取自定义的JSON文件,首先将JSON文件放置在resources/base/profile目录下。然后使用ResourceManager读取文件内容,并解析为JSON对象。示例代码如下:

import ohos.global.resource.ResourceManager;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;

ResourceManager resourceManager = getResourceManager();
RawFileEntry rawFileEntry = resourceManager.getRawFileEntry("resources/base/profile/yourfile.json");
Resource resource = rawFileEntry.openRawFile();
InputStream inputStream = resource.getRawFileDescriptor().getFileDescriptor();
String jsonString = new Scanner(inputStream).useDelimiter("\\A").next();
JSONObject jsonObject = new JSONObject(jsonString);

确保在config.json中正确配置资源路径。

回到顶部