将JS对象转换为Dart类 [英] Convert JS object into Dart classes

查看:181
本文介绍了将JS对象转换为Dart类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用JavaScript将对象从JavaScript转换为Dart类计数器部件的最佳模式是什么?

What is the best pattern to use to convert objects from Javascript to their Dart class counter parts?

// car.dart
import 'part.dart';
class Car {
  String paintColor;
  List<Part> parts;
}

// part.dart
class Part {
  String name;
  String SKU;
}

// main.dart
import 'dart:html';
import 'dart:js';

import 'car.dart';

void main() {
  var body = document.querySelector('body');
  body.addEventListener('carSelect', loadCarHandler, false);
}

void loadCarHandler(event) {

  // this is the contents of a CustomEvent from outside dart
  // goal is to convert it into Car and Parts
  LinkedHashMap obj = event.detail;

  /*
  this is what the `obj` looks like inside the debugger
  obj = _LinkedHashMap
    :paintColor = 'Red'
    :parts = List[2]
      0 = _LinkedHashMap
        :name = 'Wheel'
        :SKU = 'Z123
      1 = _LinkedHashMap
        :name = 'Tire'
        :SKU = 'Z456'
  */

}

我应该在处理程序中进行转换吗?

允许构造函数接受LinkedHashMap并将其转换为?

创建工厂?

内置到Dart我不知道会处理这个?

Should I do a conversion in the handler?
Allow the constructor to take a LinkedHashMap and convert it there?
Create a factory?
Is there something built into Dart I'm not aware of that would handle this?

处理这个问题的首选方法是什么?

What is the preferred dart way of handling this?

推荐答案

有几个库允许从JSON数据创建Dart对象。请参见 morph dartson 序列化

There are several libraries that allow to create Dart object from JSON datas. See morph, dartson or serialization.

您还可以通过添加如下所示的构造函数来避免镜像:

You can also avoid mirrors by adding a constructor like this :

class Car {
  String paintColor;
  List<Part> parts;

  Car();
  Car.fromJson(json)
      : paintColor = json['paintColor'],
        parts = json['parts'].map((e) => new Part.fromJson(e)).toList();
}

class Part {
  String name;
  String SKU;

  Part();
  Part.fromJson(json)
      : name = json['name'],
        SKU = json['SKU'];
}

这篇关于将JS对象转换为Dart类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆