我目前正在使用 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?
阅读本文 关于序列化 Xml 节点的文档
您可以通过这种方式强制 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>";
演示
这篇关于只有一个对象时将 XML 转换为 Json 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!