Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert XML to Json Array when only one object

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?

like image 833
Bex Avatar asked Oct 28 '14 15:10

Bex


People also ask

What is the difference between {} and [] in JSON?

{} denote containers, [] denote arrays.

How do I convert XML data to JSON format?

To convert an XML document to JSON, follow these steps: Select the XML to JSON action from the Tools > JSON Tools menu. Choose or enter the Input URL of the XML document. Choose the path of the Output file that will contain the resulting JSON document.

What is the difference between JSONArray and JSONObject?

JSONObject and JSONArray are the two common classes usually available in most of the JSON processing libraries. A JSONObject stores unordered key-value pairs, much like a Java Map implementation. A JSONArray, on the other hand, is an ordered sequence of values much like a List or a Vector in Java.


2 Answers

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>";

DEMO

like image 88
meda Avatar answered Sep 30 '22 23:09

meda


In case it helps anyone, further to meda's reply. Here's how you make this work with XElement rather than xmlTextWriter and 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")));

then to convert it

 XmlDocument doc = new XmlDocument();
            doc.LoadXml(items.ToString());
            var converted JsonConvert.SerializeXmlNode(doc);
like image 35
Bex Avatar answered Sep 30 '22 23:09

Bex