json - 从 Dart 中没有类的字符串/符号创建对象的实例?

标签 json reflection dart dart-mirrors

我知道可以从这个链接中显示的符号创建一个实例:

Create an instance of an object from a String in Dart?

但这对我不起作用,因为我想做的是创建一个没有类的实例。

这个问题是因为我有一个带有内部列表的类:

class MyNestedClass {
  String name;
}

class MyClass {
  int i, j;
  String greeting;
  List<MyNestedClass> myNestedClassList;
}

我想将 map 转换为此类:

   {
        "greeting": "hello, there",
        "i": 3,
        "j": 5,
        "myNestedClassList": [
           {
             "name": "someName1"
           },{
             "name": "someName2"
           }
        ]
    }

现在我正在做这样的事情:

 static void jsonToObject(String jsonString, Object object) {
    Map jsonMap = JSON.decode(jsonString); //Convert the String to a map
    mapToObject(jsonMap, object); //Convert the map to a Object
  }

  static void mapToObject(Map jsonMap, Object object) {
    InstanceMirror im = reflect(object); //get the InstanceMirror of the object
    ClassMirror cm = im.type; //get the classMirror of the object

    jsonMap.forEach((fieldNameStr, fieldValue) { // For each element in the jsonMap
      var fieldName = new Symbol(fieldNameStr); // convert the fieldName in the Map to String

      if (isPrimitive(fieldValue)) { // if fieldValue is primitive (num, string, or bool
              im.setField(fieldName, fieldValue); //set the value of the field using InstanceMirror
      } else if (fieldValue is List) { // else if the fieldValue is a list
          ClassMirror listCm = (cm.declarations[fieldName] as VariableMirror).type; //get the class mirror of the list
          var listReflectee = listCm.newInstance(const Symbol(''), []).reflectee; //create an instance of the field

          for(var element in fieldValue) { //for each element in the list
            if(!isPrimitive(element)) { // if the element in the list is a map (i.e not num, string or bool)
               var listType = listCm.typeArguments[0]; //get the TypeMirror of the list (i.e MyNestedClass from List<MyNestedClass>)

               //This is the line that doesn't work correctly
               //It should be something like:
               //
               //     ClassMirror.fromSymbol(listType.simpleName).newInstance(const Symbol(''), []);
               //
               var listObject = (listType as ClassMirror).newInstance(const Symbol(''), []); //create an instance of the specified listType

               mapToObject(element, listObject); //convert the element to Object
            }
            listReflectee.add(element); //add the element to the list
          };
      } else { //else (the field value is a map
        ClassMirror fieldCm = (cm.declarations[fieldName] as VariableMirror).type; // get the field ClassMirror from the parent declarations
        var reflectee = fieldCm.newInstance(const Symbol(''), []).reflectee; //create an instance of the field
        mapToObject(fieldValue, reflectee); // convert the fieldValue, which is a map, to an object
        im.setField(fieldName, reflectee); // set the value of the object previously converted to the corresponding field
      }
    });
  }

如您所见,实际上不起作用的行是:

var listType = listCm.typeArguments[0]; //get the TypeMirror of the list (i.e MyNestedClass from List<MyNestedClass>)
var listObject = (listType as ClassMirror).newInstance(const Symbol(''), []); //create an instance of the specified listType

因为他们在 localClassMirror 而不是 MyNestedClass 上创建实例。我正在寻找类似于以下的方法:

 ClassMirror.fromSymbol(listType.simpleName).newInstance(const Symbol(''), []);

您可以在下一个网址中看到完整的源代码:

DSON Source Code

最佳答案

如果您有类的完整限定名,您应该能够使用 libraryMirror 找到类型,然后它应该类似于您创建实例的链接问题。 我自己还没有这样做,手头也没有代码。

另请参阅:how to invoke class form dart library string or file

另一种方法是在应用程序初始化时创建一个映射,您可以在其中使用名称或 ID 注册支持的类型,并在该映射中查找类型(这就像在 Go 中完成的一样)

关于json - 从 Dart 中没有类的字符串/符号创建对象的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22704431/

相关文章:

json - 获取 package.json 文件中另一个字段的值(npm)

json - 使用 JSON 文件在 MapKit 中添加 Swift 注释

Java 接口(interface)反射

java - 非法参数异常 : wrong number of arguments

dart - 如何从Dart书架式静态文件处理程序为聚合物应用程序提供服务?

dart - 是否可以在构造函数中调用异步方法?

dart - 如何简单地同步获取 url 主体作为字符串

javascript - 评估预请求脚本时出错

javascript - 如何使用 D3.js 访问 JSON 数据?

scala - 如何使用反射评估惰性值?