问题
How to convert Object to List (array bytes) I have instance (some object) from class MyClass and I want to get bytes from this object. How implement this?
Code:
class MyClass {}
var myClass = MyClass()
List<int> getBytesFromObject(Object object) {
??? what here should be ???
}
so I can use it like:
List<int> bytes = getBytesFromObject(myClass)
回答1:
There are no builtin way to serialize Dart objects to binary. But you can convert Dart objects into JSON string and convert this string into a byte array (and later convert the byte array back to a string and convert this string to objects). Both of this are part of "dart:convert" package:
https://api.dartlang.org/stable/2.2.0/dart-convert/json-constant.html
https://api.dartlang.org/stable/2.2.0/dart-convert/utf8-constant.html
Notice that you need to manually implement the "toJson()" method on your custom classes. There are packages which can help you generate the necessary code:
https://pub.dartlang.org/packages/json_serializable
回答2:
You can use the java stream concept, whitch basically let you convert any object to an Array that you can convert it in a list with the method Arrays.asList(). Here's a simpke example:
List objectToList(Object obj){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
byte [] data = bos.toByteArray();
return data.asList();
}
来源:https://stackoverflow.com/questions/55632438/how-to-convert-object-to-bytearray-any-object-to-listint