2015-04-01 175 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/>)。