Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...