dart 将对象转换为可编码对象失败:“SharedString”的示例

vbkedwbf  于 2024-01-03  发布在  其他
关注(0)|答案(1)|浏览(149)

试图使用josnEncode()Map转换为JSON,但它抛出了

  1. Converting object to an encodable object failed: Instance of 'SharedString'
  2. #0 _JsonStringifier.writeObject (dart:convert/json.dart:793:7)
  3. #1 _JsonStringifier.writeMap (dart:convert/json.dart:874:7)
  4. #2 _JsonStringifier.writeJsonValue (dart:convert/json.dart:829:21)
  5. #3 _JsonStringifier.writeObject (dart:convert/json.dart:784:9)
  6. #4 _JsonStringStringifier.printOn (dart:convert/json.dart:982:17)
  7. #5 _JsonStringStringifier.stringify (dart:convert/json.dart:967:5)
  8. #6 JsonEncoder.convert (dart:convert/json.dart:345:30)
  9. #7 JsonCodec.encode (dart:convert/json.dart:232:37)
  10. excel_to_json_converter.dart:39
  11. <asynchronous suspension>

字符串
我代码:

  1. String data = jsonEncode(
  2. finalArJson,
  3. );

hts6caw3

hts6caw31#

我想你在这里能找到更好的。请检查一下这个!
[https://stackoverflow.com/questions/49753412/converting-object-to-an-encodable-object-failed][1]
您应该确保“finalArJson”中的所有对象都是实现toJson方法的类的示例,或者是JSON编码原生支持的类型(例如,int,double,String,List,Map)。
例如

  1. void main() {
  2. List<CustomObject> finalArJson = [
  3. CustomObject('value1', 42),
  4. CustomObject('value2', 99),
  5. // Add more CustomObject instances or other supported types
  6. ];
  7. // Convert List<CustomObject> to List<Map<String, dynamic>>
  8. List<Map<String, dynamic>> jsonList = finalArJson.map((obj) => obj.toJson()).toList();
  9. // Convert the entire list to a JSON-formatted string
  10. String data = jsonEncode(jsonList);
  11. print(data);
  12. }

字符串
您的自定义对象

  1. class CustomObject {
  2. String property1;
  3. int property2;
  4. CustomObject(this.property1, this.property2);
  5. // Implement the toJson method for custom objects
  6. Map<String, dynamic> toJson() {
  7. return {
  8. 'property1': property1,
  9. 'property2': property2,
  10. };
  11. }
  12. }


输出

  1. [
  2. {"property1": "value1", "property2": 42},
  3. {"property1": "value2", "property2": 99}
  4. ]


希望对你有帮助。谢谢

展开查看全部

相关问题