【发布时间】:2021-11-30 02:51:34
【问题描述】:
我正在使用 jsonDecode(jsonEncode(file)) 将 XML 文件转换为 JSON 文件。问题是当我尝试从带有索引号的 JSON 文件中获取数据时。它只打印一个字母。我在下面插入了代码。看看我的代码有没有问题。如果我尝试使用字符串获取数据,则会显示错误。
我的文件很大。所以,我只插入一小部分输出。
我已经尝试过xml2json包并且得到了输出。
但是在没有任何包的 dart 中,我们可以使用 import 'dart:convert'; 将 XML 文件转换为 JSON。通过文档,我了解到它仅适用于小文件。如果它也适用于大文件,我想知道这段代码中的问题和解决方案。
这就是我在下面的代码中尝试的。
这是我的代码,
Future<String> decodexml() async {
final file =
await rootBundle.loadString('assets/xml_file/belovedskincare.xml');
final jsonData = jsonDecode(jsonEncode(file));
debugPrint('$jsonData');
return jsonData;
}
当我打印 $jsonData 这是输出时,
<rss version="2.0"
I/flutter (24058): xmlns:excerpt="http://wordpress.org/export/1.2/excerpt/"
I/flutter (24058): xmlns:content="http://purl.org/rss/1.0/modules/content/"
I/flutter (24058): xmlns:wfw="http://wellformedweb.org/CommentAPI/"
I/flutter (24058): xmlns:dc="http://purl.org/dc/elements/1.1/"
I/flutter (24058): xmlns:wp="http://wordpress.org/export/1.2/"
I/flutter (24058): >
I/flutter (24058):
I/flutter (24058): <channel>
I/flutter (24058): <title>Beloved Skincare</title>
I/flutter (24058): <link>https://belovedskincare.com.my</link>
I/flutter (24058): <description>Food for your Skin</description>
I/flutter (24058): <pubDate>Sat, 02 Oct 2021 09:17:04 +0000</pubDate>
I/flutter (24058): <language>en-US</language>
I/flutter (24058): <wp:wxr_version>1.2</wp:wxr_version>
I/flutter (24058): <wp:base_site_url>https://belovedskincare.com.my</wp:base_site_url>
I/flutter (24058): <wp:base_blog_url>https://belovedskincare.com.my</wp:base_blog_url>
当我尝试从jsonData 打印一些数据时,这是我得到的输出,
代码:
var json = jsonData['rss'];
debugPrint('$json');
输出:
[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'
代码:
var json = jsonData[0];
debugPrint('$json');
输出:
I/flutter (24058): <
代码:
var json = jsonData[1];
debugPrint('$json');
输出:
I/flutter (24058): r
据我了解,json 文件中的每个字母似乎都单独保存在 jsonData 变量中。
【问题讨论】:
标签: json xml flutter dart xml-to-json