2015-04-01 164 views
0

我有以下xml;JSON.Net将XML转换为JSON

<?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" 
     }   
     ] 
    }, 
+0

什么是XslMapper类?它是你创建的还是它是第三方库的一部分? – Ulric

回答

1

Converting between JSON and XML包含一个名为属性例如强制JSON数组它说,你必须定义一个JSON命名空间

xmlns:json='http://james.newtonking.com/projects/json' 
在XML的根元素

,并添加属性

json:Array='true' 

添加到您希望转换为数组的元素(<category/>)。