JSON.Net将XML转换为JSON

时间:2015-04-01 21:12:17

标签: c# xml json json.net

我有以下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"
        }        
      ]
    },

1 个答案:

答案 0 :(得分:1)

Converting between JSON and XML包含名为强制JSON数组的属性的示例,该示例表明您必须定义JSON名称空间

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

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

json:Array='true'

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