HarmonyOS websocket拿到的返回值value如何便捷解析为嵌套对象?

自定义websocket返回值结构为

export class SocketResult<T> {
  type: string = '';
  sid?: string = '';
  identifier: T | undefined;  //object
  message: T | undefined;
}

socket 返回值字符串value,如何将value解析为

{
  type:'confirm',
  identifier:{...}
}

结构呢

identifier的值也必须用class声明,将属性都列举出来吗

阅读 571
1 个回答

identifier的值具体类型也需要定义出来,可参考以下demo:

export class SocketResult<T> {
  type: string = '';
  sid?: string = '';
  identifier: T | undefined;
  message: T | undefined;
}

// 示例返回值字符串
const value = '{"type":"confirm","identifier":{"key":"value"},"message":{}}';

// 定义具体的 identifier 类型
interface IdentifierType {
  key: string;
}

// 解析返回值字符串并转换为指定结构
const parsedValue = JSON.parse(value) as SocketResult<IdentifierType>;

// 检查并处理解析后的结果
if (parsedValue.type === 'confirm' && parsedValue.identifier) {
  console.log('解析成功', parsedValue.identifier);
} else {
  console.log('解析失败');
}

或者可以参考三方库class-transformer实现,参考文档: https://gitee.com/openharmony-tpc/openharmony\_tpc\_samples/tree/master/class-transformer

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进