Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
247 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...