首页 > 解决方案 > 如何从此 json 字段中获取数据?

问题描述

你好吗?

我正在尝试从 json 获取数据以显示在应该如下图所示的屏幕上。我能够获取大部分数据,除了一个编码为字符串的字段,它由图像和这样的描述组成:

"lessonText": "{\"ops\":[{\"insert\":{\"image\":\"data:image/jpeg;base64,(IMAGE CODE HERE)=\"}},{\"attributes\":{\"color\":\"#444444\"},\"insert\":\"(LESSON TEXT HERE)\"},{\"insert\":\"\\n\"}]}",

如何从这里提取数据?我试图将其转换为地图,但它不起作用。

谢谢您的帮助!

所需画面

标签: jsonflutterdart

解决方案


与此相符的东西应该会给您图像

// json string containing the base64 image string
String jsonString = "{\"ops\":[{\"insert\":{\"image\":\"data:image/png;base64,(IMAGE CODE HERE)=\"}},{\"attributes\":{\"color\":\"#444444\"},\"insert\":\"(LESSON TEXT HERE)\"},{\"insert\":\"\\n\"}]}";

// convert the string to a map structure
Map<String, dynamic> json = jsonDecode(jsonString);

// extract the image string
String imageString = json['ops'][0]['insert']['image'];

// extract the base64 string
var prefix = "data:image/png;base64,";
var imageBase64String = imageString.substring(prefix.length);

// decode the base 64 string
var bytes = base64Decode(imageBase64String);

// build the image widget from bytes
var imageWidget = Image.memory(bytes);

推荐阅读