HarmonyOS JSON转对象失败

在使用JSON基础API的时候发现,JSON转换失败

示例如下:

let str = `{"switchConfig":[{"name":"bizLine","status":1,"configVal":"{\"bizType\":\"1\",\"desc\":\"一课直播通用\"}"}]}`


static isJSONStr(str: string): boolean {
  try {
    JSON.parse(str);
    return true;
  } catch (error) {
    return false;
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

对于这样的JSON字符串转对象需要如何处理

HarmonyOS
2024-12-23 16:10:35
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
put_get

对于多层嵌套的json数据,可以采用reflect-metadata(参考文档:https://gitee.com/openharmony-tpc/openharmony_tpc_samples/tree/master/reflect-metadata)和class-transformer(参考文档:https://gitee.com/openharmony-tpc/openharmony_tpc_samples/tree/master/class-transformer#%E7%BA%A6%E6%9D%9F%E4%B8%8E%E9%99%90%E5%88%B6)来解决。以下是参考demo:

import { Type, plainToClass } from 'class-transformer'
import 'reflect-metadata'

class ResponseObj {
  @Type (() => SwitchConfigItem)
  switchConfig: SwitchConfigItem[] = [];
}

export class SwitchConfigItem {
  name: string = ''
  status: number = 1
  configVal: string = ''
}
@Entry
@Component
struct transFormer {
  aboutToAppear(): void {
    let str:Record<string,ESObject> = {"switchConfig":[{"name":"bizLine","status":1,"configVal":"{\"bizType\":\"1\",\"desc\":\"一课直播通用\"}"}]}
    let strObj:ResponseObj = plainToClass(ResponseObj,str);
    let configValJSON = strObj.switchConfig[0].configVal;
    console.log(`asasd:${strObj.switchConfig[0].status}`)
    console.log(`configValJSON:`,configValJSON)
    console.log(`configValJSON1:`,JSON.parse(configValJSON).desc)
  }
  build() {
  }
}
  • 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.
分享
微博
QQ
微信
回复
2024-12-23 17:38:43
相关问题
HarmonyOS mapjson对象
949浏览 • 1回复 待解决
HarmonyOS json对象map类型
1058浏览 • 1回复 待解决
如何将JSON字符串Class对象
1161浏览 • 1回复 待解决
如何将JSON字符串Class对象数组?
1270浏览 • 1回复 待解决
HarmonyOS JSON怎么Map?
1190浏览 • 1回复 待解决
HarmonyOS hashmap如何json格式?
947浏览 • 1回复 待解决
HarmonyOS Resource对象string报错
704浏览 • 1回复 待解决
HarmonyOS JSON实体类
702浏览 • 1回复 待解决
HarmonyOS mapjson怎么实现?
723浏览 • 1回复 待解决
HarmonyOS 关于JSON模问题
769浏览 • 1回复 待解决
HarmonyOS PBArrayBuffer发送失败
547浏览 • 1回复 待解决
HarmonyOS json转换失败
657浏览 • 1回复 待解决
HarmonyOS 关于jsonmodel的处理
951浏览 • 1回复 待解决
HarmonyOS Jsonmap该使用哪个接口
894浏览 • 1回复 待解决
HarmonyOS 如何创建json对象
1270浏览 • 1回复 待解决
HarmonyOS JSON对象转换
928浏览 • 1回复 待解决
如何实现MapJSON字符串
2054浏览 • 1回复 待解决