在Flutter中如何将API返回的XML响应转换为JSON?
在Flutter中将XML API响应转换为JSON
步骤1:确认依赖配置
确保pubspec.yaml中已添加所需依赖:
dependencies: xml: ^6.5.0 # 使用最新稳定版本
dart:convert是Dart内置包,无需额外添加,用于后续JSON编码。
步骤2:解析XML响应
先把API返回的XML字符串解析为XmlDocument对象:
import 'package:xml/xml.dart'; // 替换为你的实际API请求逻辑,获取XML响应字符串 String xmlResponse = await fetchXmlFromApi(); XmlDocument xmlDoc = XmlDocument.parse(xmlResponse);
步骤3:编写XML转JSON的递归转换函数
由于XML和JSON结构存在差异(XML支持重复节点、属性,JSON以键值对/数组为核心),需要递归处理每个节点:
import 'dart:convert'; dynamic xmlToJson(XmlNode node) { // 处理文本节点 if (node is XmlText) { final trimmedText = node.text.trim(); return trimmedText.isEmpty ? null : trimmedText; } // 处理元素节点 if (node is XmlElement) { // 提取节点属性 final attributes = <String, dynamic>{}; for (final attr in node.attributes) { attributes[attr.name.local] = attr.value; } // 过滤有效子节点(排除空文本节点) final validChildren = node.children.where((child) => child is XmlElement || (child is XmlText && child.text.trim().isNotEmpty) ); // 无有效子节点的情况 if (validChildren.isEmpty) { return attributes.isNotEmpty ? attributes : null; } final result = <String, dynamic>{}; final tagCount = <String, int>{}; for (final child in validChildren) { if (child is XmlElement) { final tagName = child.name.local; tagCount[tagName] = (tagCount[tagName] ?? 0) + 1; final childValue = xmlToJson(child); if (tagCount[tagName] == 1) { result[tagName] = childValue; } else if (tagCount[tagName] == 2) { // 首次出现重复标签,转为数组 result[tagName] = [result[tagName], childValue]; } else { // 后续重复标签,直接添加到数组 (result[tagName] as List).add(childValue); } } } // 将属性合并到结果中(用@attributes标识,可按需修改键名) if (attributes.isNotEmpty) { result['@attributes'] = attributes; } return result; } return null; }
步骤4:执行转换并处理数据
// 从XML根节点开始转换为JSON格式的Map final jsonData = xmlToJson(xmlDoc.rootElement) as Map<String, dynamic>; // 可选:转为JSON字符串 final jsonString = jsonEncode(jsonData); print(jsonString); // 直接使用Map提取数据 final userName = jsonData['user']['name']; print(userName);
关键说明
- 重复的XML标签会自动转为JSON数组,比如多个
<hobby>节点会变成"hobbies": ["Coding", "Reading"] - 节点属性会被统一放在
@attributes键下,可根据业务需求调整这个标识键名 - 若XML结构包含命名空间或特殊格式,可在转换函数中针对性调整逻辑
内容的提问来源于stack exchange,提问作者Jawad Abbasi
相关产品推荐
相关产品推荐

