How to convert Object to bytearray (any object to List<int>)

我怕爱的太早我们不能终老 提交于 2020-08-09 11:36:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!