HarmonyOS 如何将HashMap转换成json再UTF-8编码,再base64编码?

{
  osType : 01
  appVersion : 1.7.7
  dvImei : 864db36640ec680a2b09252fd161f43ec2b10c7d
  nonceStr : 20240524105344581032267853167626
  osVersion : 14.8.1
  txnTm : 20240524105422
  appChlNo : 04
}

如何将hasmap转换成json再UTF-8编码,再base64编码

原有项目逻辑如下

headValue = [[NSString alloc] initWithData:[self.headerDict toJSON] encoding:NSUTF8StringEncoding];

[paramDict setValue:[RMSecurityUtil encodeBase64String:headValue] forKey:@"txnHeaderInfo"];
阅读 521
1 个回答

请您参考如下代码:

import HashMap from '@ohos.util.HashMap';
import util from '@ohos.util';

function hashMap2Json() {
  const hashMap: HashMap<string, string> = new HashMap();
  hashMap.set("osType", "01");
  hashMap.set("appVersion", "1.7.7");
  hashMap.set("dvImei", "864db36640ec680a2b09252fd161f43ec2b10c7d");
  hashMap.set("nonceStr", "20240524105344581032267853167626");
  hashMap.set("osVersion", "14.8.1");
  hashMap.set("txnTm", "20240524105422");
  hashMap.set("appChlNo", "04");
  const jsonObject: Record<string, Object> = {};
  hashMap.forEach((value, key) => {
    if (key != undefined && value != undefined) {
      jsonObject[key] = value;
    }
  })
  const jsonString = JSON.stringify(jsonObject);
  console.log('jsonString', jsonString);
  return jsonString;
}
@Entry
@Component
struct TestHashMap {
  @State message: string = 'Hello World';
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            const temp = hashMap2Json();
            const json2encodeUtf8 =new util.TextEncoder().encodeInto(temp);
            console.log('json2encodeUtf8: ' + json2encodeUtf8);
            const utf82Base64 =new util.Base64Helper().encodeToStringSync(json2encodeUtf8);
            console.log('utf82Base64: ' + utf82Base64);
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进