2017-09-16 39 views
1

我使用JSON.NET将一些XML转换为JSON。强制JSON.NET将xml转换为json数组

我的XML看起来是这样的:

<Root> 
    <Product> 
     <Name /> 
     <Id /> 
    </Product> 
    <Product> 
     <Name /> 
     <Id /> 
    </Product> 
</Root> 

进出口使用这种方法转换XML:

private string ConvertToJson(string xml) 
{ 
    XmlDocument XmlDoc = new XmlDocument(); 
    XmlDoc.LoadXml(xml); 

    var JsonString = JsonConvert.SerializeXmlNode(XmlDoc); 
    return JsonString; 
} 

这只要有一个以上的产品做工精细,JSON.NET将创建一个JSON数组。 但是,如果只有一个产品JSON.NET不会创建一个JSON数组,但我需要它。

任何方式强制它创建一个JSON数组?

+0

这里的节点强制阵列代是专门针对一个答案'XmlDocument':[JSON.Net Xml序列化误解数组](https://stackoverflow.com/a/26505198/3744182)。 – dbc

回答

3

如果您知道XML模式事先可以通过附加json:Array="true"到要转换为数组

static string convertToJson(string what) 
{ 
    XmlDocument doc = new XmlDocument(); 
    doc.LoadXml(what); 

    var products = doc.GetElementsByTagName("Product"); 

    if (products.Count == 1) 
    { 
     var attribute = doc.CreateAttribute("json", "Array", "http://james.newtonking.com/projects/json"); 
     attribute.InnerText = "true"; 
     var node = products.Item(0) as XmlElement; 
     node.Attributes.Append(attribute); 
    } 

    string json = JsonConvert.SerializeXmlNode(doc); 

    return json; 
} 
0

如果您从您的XML文档(您需要知道内容结构并使用POCO对象)在您的代码中创建一个对象数组,然后使用json序列化该列表,它不应该影响您的性能。在你的情况下有意义吗?