You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中XML转JSON时如何保留数值等原始数据类型?

XML转JSON自动保留原始数据类型的解决方案

默认使用JsonConvert.SerializeXmlNode转换时,所有XML节点值都会被序列化为字符串类型,无法满足动态结构XML的类型保留需求。以下是可行的解决思路:

核心方案:自定义类型转换逻辑,递归处理JSON节点

先将XML转换为JObject,再递归遍历所有节点,尝试将字符串值转换为对应的数值、日期、布尔等类型。

实现代码

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Xml;

public class XmlToJsonTypeConverter
{
    // 将字符串值尝试转换为合适的类型
    private static JToken ConvertToProperType(string value)
    {
        // 优先判断整数
        if (int.TryParse(value, out int intVal))
            return JValue.Create(intVal);
        
        // 再判断浮点数
        if (double.TryParse(value, out double doubleVal))
            return JValue.Create(doubleVal);
        
        // 判断布尔值
        if (bool.TryParse(value, out bool boolVal))
            return JValue.Create(boolVal);
        
        // 判断日期(可根据实际需求调整格式)
        if (DateTime.TryParse(value, out DateTime dateVal))
            return JValue.Create(dateVal);
        
        // 无法转换则保留字符串
        return JValue.Create(value);
    }

    // 递归处理JObject中的所有节点
    private static void ProcessJObject(JObject obj)
    {
        foreach (var prop in obj.Properties().ToList())
        {
            // 处理字符串类型的值
            if (prop.Value.Type == JTokenType.String)
            {
                string strValue = prop.Value.ToString();
                prop.Value = ConvertToProperType(strValue);
            }
            // 递归处理嵌套对象
            else if (prop.Value.Type == JTokenType.Object)
            {
                ProcessJObject((JObject)prop.Value);
            }
            // 处理数组中的元素
            else if (prop.Value.Type == JTokenType.Array)
            {
                foreach (var item in (JArray)prop.Value)
                {
                    if (item.Type == JTokenType.Object)
                        ProcessJObject((JObject)item);
                    else if (item.Type == JTokenType.String)
                        item.Replace(ConvertToProperType(item.ToString()));
                }
            }
        }
    }

    // 对外暴露的转换方法
    public static string ConvertXmlToTypedJson(string xmlString)
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xmlString);

        // 先将XML转为JObject
        string tempJson = JsonConvert.SerializeXmlNode(doc, Formatting.None, true);
        JObject jsonObj = JsonConvert.DeserializeObject<JObject>(tempJson);

        // 处理类型转换
        ProcessJObject(jsonObj);

        // 输出格式化后的JSON
        return JsonConvert.SerializeObject(jsonObj, Formatting.Indented);
    }
}

使用示例

string xml = @"<root>
    <deviceToEgressLocationDistance>600</deviceToEgressLocationDistance>
    <Location1>500.88</Location1>
    <Location2>650</Location2>
    <InstallDate>2024-05-20</InstallDate>
    <IsActive>true</IsActive>
</root>";

string typedJson = XmlToJsonTypeConverter.ConvertXmlToTypedJson(xml);
Console.WriteLine(typedJson);

输出结果

{
  "deviceToEgressLocationDistance": 600,
  "Location1": 500.88,
  "Location2": 650,
  "InstallDate": "2024-05-20T00:00:00",
  "IsActive": true
}

注意事项

  • 类型判断顺序:必须优先判断整数再判断浮点数,避免整数被错误转换为浮点数。
  • 日期格式适配:如果XML中的日期格式非标准,可改用DateTime.TryParseExact指定匹配格式。
  • 嵌套结构兼容:递归逻辑会处理所有嵌套对象和数组,适配任意动态XML结构。

内容的提问来源于stack exchange,提问作者Jimmy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 04:54:16