I am currently using Newtonsoft to convert some xml to json to return from a RestExtension.
My xml is in the form of
<Items>
<Item>
<Name>name</Name>
<Detail>detail</Detail>
</Item>
<Item>
<Name>name</Name>
<Detail>detail</Detail>
</Item>
</Items>
I convert this to json using
JsonConvert.SerializeXmlNode(xmldocument);
This works fine if there is more than one item.
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"}}}
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?
Read this documentation about Serialize Xml Node
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>";