当只有一个对象时将XML转换为Json Array [英] Convert XML to Json Array when only one object
问题描述
我目前正在使用Newtonsoft将xml转换为json,以从RestExtension返回.
I am currently using Newtonsoft to convert some xml to json to return from a RestExtension.
我的xml格式为
<Items>
<Item>
<Name>name</Name>
<Detail>detail</Detail>
</Item>
<Item>
<Name>name</Name>
<Detail>detail</Detail>
</Item>
</Items>
我使用
JsonConvert.SerializeXmlNode(xmldocument);
如果有多个项目,则此方法工作正常.
This works fine if there is more than one item.
我明白了-json中的一系列项目(这是我需要的):
I get this - an array of items in json (which is what I need):
{"Items":{"Item":[{"Name":"name","Detail":"detail"},{"Name":"name","Detail":"detail"}]}}
但是当只有一个时,它可以这样转换(而不是数组):
But when there is only one it quite understandably converts like this (not an array):
{"Items":{"Item":{"Name":"name","Detail":"detail"}}}
正在阅读此内容的我的应用程序开发人员需要json返回一组项,无论是否存在一个或多个.
My app developer who is reading this needs the json to return an array of items regardless or whether there is one or more.
有没有一种方法可以欺骗它,使其认为它是数组,或者有人可以提出另一种方法来做到这一点?
Is there a way of tricking it into thinking it's an array or can someone suggest another way of doing this?
推荐答案
您可以通过这种方式强制使用JSON数组
You can force JSON Array this way
var xml = @"<Items xmlns:json='http://james.newtonking.com/projects/json' >
<Item json:Array='true'>
<Name>name</Name>
<Detail>detail</Detail>
</Item>
</Items>";
DEMO
这篇关于当只有一个对象时将XML转换为Json Array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!