16

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?

9
  • Sorry What do you want to be an array not sure I followed the question properly Commented Oct 28, 2014 at 15:57
  • sorry I've edited to hopefully make it clearer. I need an array of items. Commented Oct 28, 2014 at 15:59
  • 1
    @DJkraze he has done the conversion he just needs needs it it a different format Commented Oct 28, 2014 at 16:01
  • @DJKRAZE, the link you sent is exactly what I am doing. I just need it differently. Unless I am totally missing the point, please either explain or be kind enough to retract your down vote. Commented Oct 28, 2014 at 16:05
  • ok can you do something like the following since I can't tell which format is correct or not from your question XmlNote myXmlNode = JsonConvert.DeserializeXmlNode(yourJsonString); // or .DeserilizeXmlNode(myJsonString, "root"); // if yourJsonString does not have a root string jsonString = JsonConvert.SerializeXmlNode(myXmlNode); Commented Oct 28, 2014 at 16:05

4 Answers 4

17

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

Sign up to request clarification or add additional context in comments.

4 Comments

that's great! Would you happen to know how you'd generate that with XElement as it doesn't like the ":"?
thanks I understand now.have put a post below how I'd do it with XElement rather than xmltextwritera and XDocument
This is a little difficult to do once the XML document is already in memory. However the namespace can be added to the node directly using the XmlNode.Attributes.Append(XMLAttribute) method. You will get: <Item json:Array='true' xmlns:json='james.newtonking.com/projects/json'> which will also work.
@meda How do you keep the json:Array attibutes when converting xml to json and then again to xml and back to json? Question: stackoverflow.com/q/48763666/7392294
4

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

Comments

1

Cinchoo ETL - an open source library available to convert such xml into expected json format

string xml = @"<Items>
        <Item>
            <Name>name</Name>
            <Detail>detail</Detail>    
        </Item>
    </Items>";

StringBuilder sb = new StringBuilder();
using (var p = ChoXmlReader.LoadText(xml).WithXPath("/"))
{
    using (var w = new ChoJSONWriter(sb)
        .Configure(c => c.SupportMultipleContent = true)
        )
        w.Write(p);
}

Console.WriteLine(sb.ToString());

Output:

{
 "Items": [
  {
    "Name": "name",
    "Detail": "detail"
  }
 ]
}

Disclaimer: I'm the author of this library.

Comments

0
public class WSDLReport
{
    private IEnumerable<WSDLDocument> _document;

    private void SetDocuments(dynamic documents)
    {
        var type = documents.GetType();

        if (type == typeof(JObject))
            _document = new List<WSDLDocument>() { ((JObject)documents).ToObject<WSDLDocument>() };
        else if (type == typeof(JArray))
            _document = ((JArray)documents).ToObject<IEnumerable<WSDLDocument>>();
        else
            _document = new List<WSDLDocument>();
    }

    private dynamic GetDocuments() => _document;

    [JsonProperty("dokumentyEzla")]
    public dynamic Document
    {
        get => GetDocuments();
        set => SetDocuments(value);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.