← Back to list

How to read a Custom JSON file in HarmonyOS using getRawFileContent?

Custom JSON files in HarmonyOS are simple to handle once you know they belong to raw resources.

Mehmet Algul in Huawei Developers · 2025-12-15 14:09 · 50 claps · 2.6 min read
#harmony-os #ark-ts #ark-ui #json #raw-file
Open on Medium ↗

How to read a Custom JSON file in HarmonyOS using getRawFileContent?

Generated by AI

Generated by AI

Custom JSON files in HarmonyOS are simple to handle once you know they belong to raw resources. Use getRawFileContent() and you're good to go.

Introduction

Many developers transitioning into HarmonyOS expect resource handling to behave similarly to Android or other mobile platforms. However, when working with custom files — especially JSON — HarmonyOS uses a different resource architecture. As a result, trying to load a JSON file using APIs like getStringArrayValueSync() quickly leads to confusion.

In this guide, we’ll break down why JSON files cannot be accessed using element resource APIs, explain the correct approach using getRawFileContent(), and provide a fully working ArkTS example you can use directly in your project.

The Core Problem: JSON Files Are Not Element Resources

A common mistake is trying to read a JSON file such as intarray.json using:

resourceManager.getStringArrayValueSync()

This API only works with element resources placed under:

resources/base/element/

Json file

Json file

Supported types include:

  • string
  • string-array
  • boolean-array
  • plural

However, custom JSON files do not belong to this category. Because of this, HarmonyOS cannot parse or access them through standard element resource functions.

They must be treated as raw files.

Correct Solution: Use getRawFileContent()

HarmonyOS provides a dedicated API for loading non-element files:

getRawFileContent()

You must place your file under:

resources/rawfile/

This API returns the file as a Uint8Array, which you then convert:

Uint8Array → string → JSON → object

Project Setup: Where to Put Your JSON File

Place your file here:

resources/rawfile/intarray.json

Example JSON Content

{
  "intarray": {
    "item1": { "name": "aaa", "value": [1, 2, 3] },
    "item2": { "name": "bbb", "value": [4, 5, 6] }
  }
}

Full Working ArkTS Example

Below is a complete, ready-to-run example demonstrating how to read and parse a custom JSON file using HarmonyOS APIs.

import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { buffer, JSON } from '@kit.ArkTS';

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  private context = getContext(this) as common.Context;

  aboutToAppear(): void {
    try {
      this.context.resourceManager.getRawFileContent('intarray.json')
        .then((value: Uint8Array) => {
          let strParam = buffer.from(value.buffer).toString()
          let obj = JSON.parse(strParam) as Record<string, object>
          let array = obj['intarray'] as Record<string, Array<number>>

          Object.keys(array).forEach(key => {
            if (array[key]['name'] == 'aaa') {
              console.log(key, array[key]['value']);
            }
          });

          console.log('Get Value:' + JSON.stringify(array))
        })
        .catch((error: BusinessError) => {
          console.error("getRawFileContent promise error is " + error);
        });
    } catch (error) {
      let code = (error as BusinessError).code;
      let message = (error as BusinessError).message;
      console.error(`promise getRawFileContent failed, error code: ${code}, message: ${message}.`);
    }

  }

  build() {
    Column() {
      Text(this.message)
        .id('HelloWorld')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
    }
    .height('100%')
    .width('100%')
  }
}

How It Works (Step-by-Step)

1. Load the raw file

this.context.resourceManager.getRawFileContent('intarray.json')

Returns a Uint8Array.

2. Convert bytes → string

let strParam = buffer.from(value.buffer).toString()

3. Parse JSON

let obj = JSON.parse(strParam)

4. Access the inner data

let array = obj['intarray']

5. Iterate or filter the items

if (array[key]['name'] == 'aaa') {
  console.log(array[key]['value'])
}

Key Takeaways

  • JSON files are not element resources

So, element-based APIs cannot read them.

  • Custom files must live here:
resources/rawfile/
  • Use this API:
getRawFileContent()
  • Always parse the raw bytes manually:
Uint8Array → Buffer → String → JSON.parse()

Conclusion

Working with custom JSON files in HarmonyOS is straightforward once you understand the architecture. The key is knowing that these files are not element resources and must be accessed through getRawFileContent().

By following the approach in this guide, you’ll have full control over loading and parsing any JSON file in your HarmonyOS application.

References

[embed]Document The OpenCms demo, brought to you by Alkacon Software.developer.huawei.com

[embed]HUAWEI Developer Forum | HUAWEI Developer Edit descriptionforums.developer.huawei.com


메타데이터
post_id
5f8d11059d7d
slug
how-to-read-a-custom-json-file-in-harmonyos-using-getrawfilecontent-5f8d11059d7d
url
https://medium.com/huawei-developers/how-to-read-a-custom-json-file-in-harmonyos-using-getrawfilecontent-5f8d11059d7d
canonical_url
https://medium.com/huawei-developers/how-to-read-a-custom-json-file-in-harmonyos-using-getrawfilecontent-5f8d11059d7d
author_url
https://medium.com/@mehmetalgul97
status
ok
fetched_at
2026-07-14 05:04:12