仅在一个对象时将XML转换为Json数组

时间:2014-10-28 15:56:06

标签: c# .net xml json json.net

我目前正在使用Newtonsoft将一些xml转换为json以从RestExtension返回。

我的xml采用

的形式
<Items>
  <Item>
    <Name>name</Name>
    <Detail>detail</Detail>    
  </Item>
  <Item>
    <Name>name</Name>
    <Detail>detail</Detail>    
  </Item>
</Items>

我使用

将其转换为json
JsonConvert.SerializeXmlNode(xmldocument);

如果有多个项目,这可以正常工作。

我得到了这个 - json中的一个项目数组(这是我需要的):

{"Items":{"Item":[{"Name":"name","Detail":"detail"},{"Name":"name","Detail":"detail"}]}}

但是当只有一个时,可以理解的是这样转换(不是数组):

 {"Items":{"Item":{"Name":"name","Detail":"detail"}}}

我正在阅读此内容的应用开发者需要json返回一个项目数组,无论是否有一个或多个。

有没有办法欺骗它认为它是一个阵列还是有人建议另一种方式这样做?

4 个答案:

答案 0 :(得分:12)

阅读此documentation about Serialize Xml Node

您可以通过这种方式强制使用JSON数组

var xml = @"<Items xmlns:json='http://james.newtonking.com/projects/json' >
             <Item json:Array='true'>
                <Name>name</Name>
                 <Detail>detail</Detail>    
            </Item>
            </Items>";

<强> DEMO

答案 1 :(得分:3)

如果它对任何人有帮助,可以进一步回复meda的回复。 以下是使用XElement而不是xmlTextWriter和XDocument

的方法
XNamespace ns = "http://james.newtonking.com/projects/json";
var items = new XElement("items",new XAttribute(XNamespace.Xmlns+"json",ns));

   items.Add(new XElement("item",new XAttribute(ns+"Array",true),
                        new XElement("name", "name"),
                        new XElement("Detail", "detail")));

然后转换它

 XmlDocument doc = new XmlDocument();
            doc.LoadXml(items.ToString());
            var converted JsonConvert.SerializeXmlNode(doc);

答案 2 :(得分:0)

Cinchoo ETL - 一个可用于将此类xml转换为预期的json格式的开源库

string xml = @"<Items>
        <Item>
            <Name>name</Name>
            <Detail>detail</Detail>    
        </Item>
    </Items>";

StringBuilder sb = new StringBuilder();
using (var p = ChoXmlReader.LoadText(xml).WithXPath("/"))
{
    using (var w = new ChoJSONWriter(sb)
        .Configure(c => c.SupportMultipleContent = true)
        )
        w.Write(p);
}

Console.WriteLine(sb.ToString());

输出:

{
 "Items": [
  {
    "Name": "name",
    "Detail": "detail"
  }
 ]
}

免责声明:我是这个图书馆的作者。

答案 3 :(得分:0)

public class WSDLReport
{
    private IEnumerable<WSDLDocument> _document;

    private void SetDocuments(dynamic documents)
    {
        var type = documents.GetType();

        if (type == typeof(JObject))
            _document = new List<WSDLDocument>() { ((JObject)documents).ToObject<WSDLDocument>() };
        else if (type == typeof(JArray))
            _document = ((JArray)documents).ToObject<IEnumerable<WSDLDocument>>();
        else
            _document = new List<WSDLDocument>();
    }

    private dynamic GetDocuments() => _document;

    [JsonProperty("dokumentyEzla")]
    public dynamic Document
    {
        get => GetDocuments();
        set => SetDocuments(value);
    }
}