简体   繁体   English

使用js-interop如何将javascript数组和对象转换为本机dart Map。

[英]Using js-interop how can I convert javascript Array and Object to native dart Map.

Is it possible to convert a javascript object or array back to native dart Map and/or List? 是否可以将javascript对象或数组转换回本机dart Map和/或List? I'm trying to get a manifest file returned from javascript as Object and want to convert it to a Dart Map object. 我正在尝试从javascript作为Object返回一个清单文件,并希望将其转换为Dart Map对象。

You can convert a javascript JSON to a Dart JSON with : 您可以使用以下命令将javascript JSON转换为Dart JSON:

import 'dart:json';
import 'package:js/js.dart' as js;

convert(js.Proxy jsonProxy) => JSON.parse(js.context.JSON.stringify(jsonProxy));

You could use the built in Javascript method JSON.stringify() from the Javascript context. 您可以使用Javascript上下文中内置的Javascript方法JSON.stringify()。

Future getManifest() {
  var completer = new Completer();

  js.scoped(() {
    var chrome = js.context.chrome; 
    var manifest_proxy = chrome.runtime.getManifest();
    var manifest_string = js.context.JSON.stringify(manifest_proxy);
    var manifest = JSON.parse(manifest_string);
    logger.fine("manifest_string = $manifest_string");
    completer.complete(manifest);
  });

  return completer.future;    
}

Which would print out the following to the console and send the completer a dart Map. 这将打印出以下内容到控制台并向完成者发送一个飞镖地图。

manifest_string = {"app":{"background":{"scripts":["main.js"]}},"manifest_version":2,"minimum_chrome_version":"23","name":"chrome.dart - test","version":"1"} 

Many changes in API was done by this year, following code is Alexandre Ardhuin's answer adapted to latest (#30104) Dart Sdk API的许多变化都是在今年完成的,代码是Alexandre Ardhuin的答案适应最新的(#30104)Dart Sdk

import "dart:convert";
import "dart:js" as js;

convert( js.JsObject object )
{
  return JSON.decode( js.context['JSON'].callMethod("stringify", [ object ] ) );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM