JSON.Net 将 XML 转换为 JSON

JSON.Net Converting XML into JSON

我关注xml;

<?xml version="1.0" encoding="utf-8" ?>
<XslMapper>
  <type name="article" xsl="http://localhost:8080/Xsl-a.xslt">
    <category name="1234" xsl="http://localhost:8080/Xsl-b.xslt"></category>
    <category name="1234" xsl="http://localhost:8080/Xsl-b.xslt"></category>
  </type>
  <type name="slideshow" xsl="http://localhost:8080/Xsl-c.xslt" >
    <category name="1234" xsl="http://localhost:8080/Xsl-b.xslt"></category>
  </type>
</XslMapper>

用于解析的C#代码;

WebClient client = new WebClient();
            StringBuilder builder = new StringBuilder();
            string downloadString = client.DownloadString(XslMapperFileAddress);
            XmlDocument xml = new XmlDocument();
            xml.LoadXml(downloadString);
            XmlWriter writer = XmlWriter.Create(builder, new XmlWriterSettings() { OmitXmlDeclaration = true });
            xml.Save(writer);
            string xmlString = builder.ToString();
            xml.LoadXml(xmlString);
            string jsonText = JsonConvert.SerializeXmlNode(xml, Formatting.Indented, true);
            jsonText = Regex.Replace(jsonText, "(?<=\")(@)(?!.*\":\s )", string.Empty, RegexOptions.IgnoreCase);
            XslMapper xslMapper = JsonConvert.DeserializeObject<XslMapper>(jsonText);
            return xslMapper.XmlMapperTypes;

当我使用 json.net 将此 xml 序列化为 json 时,我得到以下结果;

{
  "type": [
    {
      "name": "article",
      "xsl": "http://localhost:8080/Services/Xsl-a.xslt",
      "category": [
        {
          "name": "1234",
          "xsl": "http://localhost:8080/Services/Xsl-b.xslt"
        },
        {
          "name": "1234",
          "xsl": "http://localhost:8080/Services/Xsl-b.xslt"
        }
      ]
    },
    {
      "name": "slideshow",
      "xsl": "http://localhost:8080/Services/Xsl-c.xslt",
      "category": {
        "name": "1234",
        "xsl": "http://localhost:8080/Services/Xsl-b.xslt"
      }
    }
  ]
}

如您所见,第一类部分被解析为数组(我打算这样做),第二部分被转换为对象。这就是为什么我从 JSON.NET

收到错误

如何将第二部分解析为数组;

"category": [
        {
          "name": "1234",
          "xsl": "http://localhost:8080/Services/Xsl-b.xslt"
        }        
      ]
    },

Converting between JSON and XML 包含名为 Attribute to Force a JSON Array 的示例,它表示您必须定义一个 JSON 命名空间

xmlns:json='http://james.newtonking.com/projects/json'

在XML的根元素中添加一个属性

json:Array='true'

到您希望转换为数组的元素(<category/> 在您的情况下)。