JHHK

欢迎来到我的个人网站
行者常至 为者常成

Json处理

目录

Json处理

map转json字符串

可以将Map转成Record后,再通过JSON.stringify()转为JSON字符串。示例如下:

let mapSource = new Map<string, string>(); 
mapSource.set('name', 'name1'); 
mapSource.set('width', '100'); 
mapSource.set('height', '50'); 
 
let jsonObject: Record<string, Object> = {}; 
mapSource.forEach((value, key) => { 
  if (key !== undefined && value !== undefined) { 
    jsonObject[key] = value; 
  } 
}) 
let jsonInfo: string = JSON.stringify(jsonObject); 
 
@Entry 
@Component 
struct Index { 
  build() { 
    Column() { 
      Button('Map to JSON') 
        .onClick(() => { 
          console.log('jsonInfo:', jsonInfo); // jsonInfo: {"name":"name1","width":"100","height":"50"} 
        }) 
    } 
  } 
}

行者常至,为者常成!





R
Valine - A simple comment system based on Leancloud.