使用C#实现指定JSON到特定格式XML转换的技术问询
自定义JSON转XML的C#实现方案(适配指定格式)
这种API返回格式固定但和需求格式不匹配的情况太常见了,既然API团队不愿意改,咱们完全可以在自己的C#代码里做自定义转换,完美实现你要的XML格式,不用动API半分。
核心思路
默认的JSON转XML工具(比如JsonConvert.DeserializeXNode)会直接把errorMessages里的键值对当成子节点名,不符合你需要的<ErrorCode>和<ErrorDescription>结构。所以咱们要手动解析JSON,然后逐个构建XML节点,完全按照需求格式来生成。
方案一:使用Newtonsoft.Json(最灵活)
这是.NET生态里处理JSON最常用的库,动态解析JSON非常方便,适合处理这种结构不固定的响应。
首先确保你已经安装了Newtonsoft.Json NuGet包,然后用下面的代码:
using Newtonsoft.Json.Linq; using System.Xml; using System.IO; public string ConvertCustomJsonToXml(string jsonResponse) { // 解析API返回的JSON字符串 var jsonObj = JObject.Parse(jsonResponse); // 初始化XML文档和根节点 XmlDocument xmlDoc = new XmlDocument(); XmlElement rootNode = xmlDoc.CreateElement("root"); xmlDoc.AppendChild(rootNode); // 处理status节点:转成大写 XmlElement statusNode = xmlDoc.CreateElement("status"); statusNode.InnerText = jsonObj["status"]?.ToString().ToUpper() ?? string.Empty; rootNode.AppendChild(statusNode); // 处理errorMessages部分 var errorMessages = jsonObj["errorMessages"] as JObject; if (errorMessages != null && errorMessages.HasValues) { XmlElement errorMessagesNode = xmlDoc.CreateElement("errorMessages"); rootNode.AppendChild(errorMessagesNode); // 遍历每个错误码和对应的描述 foreach (var errorEntry in errorMessages) { // 添加ErrorCode节点 XmlElement errorCodeNode = xmlDoc.CreateElement("ErrorCode"); errorCodeNode.InnerText = errorEntry.Key; errorMessagesNode.AppendChild(errorCodeNode); // 添加ErrorDescription节点 XmlElement errorDescNode = xmlDoc.CreateElement("ErrorDescription"); errorDescNode.InnerText = errorEntry.Value.ToString(); errorMessagesNode.AppendChild(errorDescNode); } } // 将XML文档转为格式化后的字符串 using (StringWriter sw = new StringWriter()) { using (XmlTextWriter writer = new XmlTextWriter(sw) { Formatting = Formatting.Indented }) { xmlDoc.WriteTo(writer); } return sw.ToString(); } }
方案二:使用System.Text.Json(内置无依赖)
如果你用的是.NET Core 3.0+或者.NET 5+,可以直接用内置的System.Text.Json库,不需要额外安装NuGet包:
using System.Text.Json; using System.Xml; using System.IO; public string ConvertCustomJsonToXmlWithSystemTextJson(string jsonResponse) { // 解析JSON文档 using JsonDocument jsonDoc = JsonDocument.Parse(jsonResponse); JsonElement rootElement = jsonDoc.RootElement; // 初始化XML结构 XmlDocument xmlDoc = new XmlDocument(); XmlElement xmlRoot = xmlDoc.CreateElement("root"); xmlDoc.AppendChild(xmlRoot); // 处理status节点 if (rootElement.TryGetProperty("status", out JsonElement statusElement)) { XmlElement statusNode = xmlDoc.CreateElement("status"); statusNode.InnerText = statusElement.GetString()?.ToUpper() ?? string.Empty; xmlRoot.AppendChild(statusNode); } // 处理errorMessages if (rootElement.TryGetProperty("errorMessages", out JsonElement errorMessagesElement) && errorMessagesElement.ValueKind == JsonValueKind.Object) { XmlElement errorMessagesNode = xmlDoc.CreateElement("errorMessages"); xmlRoot.AppendChild(errorMessagesNode); foreach (var errorEntry in errorMessagesElement.EnumerateObject()) { XmlElement errorCodeNode = xmlDoc.CreateElement("ErrorCode"); errorCodeNode.InnerText = errorEntry.Name; errorMessagesNode.AppendChild(errorCodeNode); XmlElement errorDescNode = xmlDoc.CreateElement("ErrorDescription"); errorDescNode.InnerText = errorEntry.Value.GetString() ?? string.Empty; errorMessagesNode.AppendChild(errorDescNode); } } // 输出格式化XML using StringWriter sw = new StringWriter(); using XmlTextWriter writer = new XmlTextWriter(sw) { Formatting = Formatting.Indented }; xmlDoc.WriteTo(writer); return sw.ToString(); }
测试验证
把你提供的JSON输入进去:
{ "status":"Error", "errorMessages":{ "1001":"Schema validation Error" } }
两种方案都会生成你需要的XML:
<root> <status>ERROR</status> <errorMessages> <ErrorCode>1001</ErrorCode> <ErrorDescription>Schema validation Error</ErrorDescription> </errorMessages> </root>
而且如果API返回多个错误码(比如errorMessages里有多个键值对),代码也能自动处理,生成对应的<ErrorCode>和<ErrorDescription>节点。
内容的提问来源于stack exchange,提问作者abhi pm
相关产品推荐
相关产品推荐

