0

我正在使用将 XML 文件转换为 JSON 文件jsonDecode(jsonEncode(file))。问题是当我尝试从带有索引号的 JSON 文件中获取数据时。它只打印一个字母。我在下面插入了代码。看看我的代码有没有问题。如果我尝试使用字符串获取数据,则会显示错误。

我的文件很大。所以,我只插入一小部分输出。

我已经尝试过 xml2json 包并且得到了输出。

但是在没有任何包的 dart 中,我们可以将 XML 文件转换为带有import 'dart:convert';. 通过文档,我了解到它仅适用于小文件。如果它也适用于大文件,我想知道这段代码中的问题和解决方案。

这就是我在下面的代码中尝试的。

这是我的代码,

 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变量中。

4

1 回答 1

0

我已经在使用 xml2json 包。

不,你没有。您的代码中没有这样的东西。您只是在调用无意义的函数,就像 XMl 数据是 json 一样。它不是,这就是你得到错误的原因。

我建议您实际阅读您正在使用的包上的示例,然后相应地编写您的代码。一个包不是你引用的魔法,然后它就可以工作。你必须调用它们的函数。

于 2021-10-11T10:58:32.987 回答