HarmonyOS 鸿蒙Next中如何将ArrayBuffer转换成对象
HarmonyOS 鸿蒙Next中如何将ArrayBuffer转换成对象 在鸿蒙http模块的流式传输中的返回值data是ArrayBuffer类型,我该如何将其转换成一个对象,方便查看返回值中的数据?
就是这个模块:
httpRequest.on('dataReceive', (data: ArrayBuffer) => {
.........
});
6 回复
转换流程
数据累积:流式传输会分多次触发dataReceive事件,需通过Uint8Array拼接数据
类型转换:利用TextDecoder将ArrayBuffer转为字符串
对象解析:通过JSON.parse()将字符串转为对象
实现代码
// 声明数据缓存区
private receivedData: Uint8Array = new Uint8Array(0);
// 流式数据接收处理
httpRequest.on('dataReceive', (chunk: ArrayBuffer) => {
// 将新数据块转为Uint8Array并与缓存合并
const newChunk = new Uint8Array(chunk);
const mergedArray = new Uint8Array(this.receivedData.length + newChunk.length);
mergedArray.set(this.receivedData);
mergedArray.set(newChunk, this.receivedData.length);
this.receivedData = mergedArray;
});
// 数据接收完成事件
httpRequest.on('dataEnd', () => {
try {
// 将累积的ArrayBuffer转为字符串
const decoder = util.TextDecoder.create('utf-8');
const jsonString = decoder.decodeWithStream(this.receivedData.buffer);
// 字符串转对象
const resultObject = JSON.parse(jsonString);
console.log('转换后的对象:', resultObject);
// 清空缓存
this.receivedData = new Uint8Array(0);
} catch (error) {
console.error('数据解析失败:', error);
}
});
更多关于HarmonyOS 鸿蒙Next中如何将ArrayBuffer转换成对象的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
背景知识:
楼主,如果是转为string字符串对象的话,直接使用 TextDecoder.create()方法。
问题解决:
示例代码:
import { util } from '@kit.ArkTS';
let data = new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f]).buffer; // 示例数据
let deviceName = util.TextDecoder.create('UTF-8', {
ignoreBOM: true
}).decodeToString(new Uint8Array(data), { stream: false });
ArrayBuffer 转 string
/**
* 将ArrayBuffer转换为字符串
* @param arr ArrayBuffer数据
* @returns 转换后的字符串
*/
function arrayBufferToStr(arr: ArrayBuffer): string {
const uint8Array = new Uint8Array(arr)
return util.TextDecoder.create().decodeToString(uint8Array)
}
想转成什么类型的对象?
在HarmonyOS鸿蒙Next中,可使用TextDecoder将ArrayBuffer转换为字符串,再通过JSON.parse转为对象。示例代码:
let buffer = new ArrayBuffer(...);
let decoder = new TextDecoder('utf-8');
let str = decoder.decode(buffer);
let obj = JSON.parse(str);
需确保ArrayBuffer包含有效的UTF-8编码JSON数据。
在HarmonyOS Next中,可以通过TextDecoder
将ArrayBuffer转换为字符串,然后解析为对象。示例如下:
httpRequest.on('dataReceive', (data: ArrayBuffer) => {
const decoder = new TextDecoder('utf-8');
const jsonString = decoder.decode(data);
const result = JSON.parse(jsonString);
console.log(result);
});
如果数据是JSON格式,直接使用JSON.parse
解析即可。注意处理可能的异常,确保数据格式正确。