Convert XML to Json Array when only one object(只有一个对象时将 XML 转换为 Json 数组)
问题描述
我目前正在使用 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 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:只有一个对象时将 XML 转换为 Json 数组


- 在 C# 中异步处理项目队列 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 使用 rss + c# 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01