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
Answer from meda on Stack OverflowRead 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
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);
There is another solution for this without using script mediator, you can add
<?xml-multiple?>
processing instruction to your payload. as follows;
<users>
<?xml-multiple?>
<user>user1</user>
</users>
this will create json array for users.
{"users": {"user": ["user1"]}}
Hope this will helpful.
If anybody looking for converting the XML to Json, the below method can be used. It encloses all JSONObject inside a JSONArray.
public JSONObject getJSONFromXML(String xml) {
JSONObject jsonObject = null;
try {
jsonObject = XML.toJSONObject(xml);
convertJsonObjectToArray(jsonObject);
} catch (JSONException e) {
System.out.println("Error in parsing JSON From xml: " + e);
}
return jsonObject;
}
private void convertJsonObjectToArray(JSONObject jsonObject) throws JSONException {
for (Object key : jsonObject.keySet()) {
Object val = jsonObject.get(key.toString());
if (val instanceof JSONObject) {
convertJsonObjectToArray((JSONObject) val);
JSONArray jsonArray = new JSONArray();
jsonArray.put(val);
jsonObject.put(key.toString(), jsonArray);
} else if (val instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) val;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = (JSONObject) jsonArray.get(i);
convertJsonObjectToArray(obj);
}
}
}
}
Having issue while convertnig xml with single element to json array or vice versa
[XmlToJson] Single Element to JSON array Error | OutSystems
jquery - Convert XML to JSON (and back) using Javascript - Stack Overflow
java - Process single element array when converting XML to JSON ( ) - Stack Overflow
If you know XML schema beforehand you can force array generation by attaching json:Array="true" to the node you want to convert to an array
static string convertToJson(string what)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(what);
var products = doc.GetElementsByTagName("Product");
if (products.Count == 1)
{
var attribute = doc.CreateAttribute("json", "Array", "http://james.newtonking.com/projects/json");
attribute.InnerText = "true";
var node = products.Item(0) as XmlElement;
node.Attributes.Append(attribute);
}
string json = JsonConvert.SerializeXmlNode(doc);
return json;
}
It shouldn't impact too much in your performance if you create an array of objects in your code from your XML doc (you need to know the content structure and use POCO objects) and then serialize that list with json. Makes it sense in your case?
I think this is the best one: Converting between XML and JSON
Be sure to read the accompanying article on the xml.com O'Reilly site, which goes into details of the problems with these conversions, which I think you will find enlightening. The fact that O'Reilly is hosting the article should indicate that Stefan's solution has merit.
https://github.com/abdmob/x2js - my own library (updated URL from http://code.google.com/p/x2js/):
This library provides XML to JSON (JavaScript Objects) and vice versa javascript conversion functions. The library is very small and doesn't require any other additional libraries.
API functions
- new X2JS() - to create your instance to access all library functionality. Also you could specify optional configuration options here
- X2JS.xml2json - Convert XML specified as DOM Object to JSON
- X2JS.json2xml - Convert JSON to XML DOM Object
- X2JS.xml_str2json - Convert XML specified as string to JSON
- X2JS.json2xml_str - Convert JSON to XML string
Online Demo on http://jsfiddle.net/abdmob/gkxucxrj/1/
var x2js = new X2JS();
function convertXml2JSon() {
$("#jsonArea").val(JSON.stringify(x2js.xml_str2json($("#xmlArea").val())));
}
function convertJSon2XML() {
$("#xmlArea").val(x2js.json2xml_str($.parseJSON($("#jsonArea").val())));
}
convertXml2JSon();
convertJSon2XML();
$("#convertToJsonBtn").click(convertXml2JSon);
$("#convertToXmlBtn").click(convertJSon2XML);
I'm late on this... but, using org.json:
public static void forceToJSONArray(JSONObject xmlJSONObj, String obj) throws org.json.JSONException
{
// where "JSONObject xmlJSONObj" is my JSONObject obtained by passing the XML throug the method toJSONObject
// and where "String obj" is the name of the JSONObject I want to force to JSONArray
Object myObj = xmlJSONObj.opt(obj);
if (myObj == null)
{
// if my obj doesn't exist inside my xmlJSONObj i create it empty
JSONArray jsonArray = new JSONArray();
xmlJSONObj.put(obj, jsonArray);
}
else if ( myObj instanceof JSONObject )
{
// if exist but is a JSONObject, I force it to JSONArray
JSONObject myJSONObj = (JSONObject)myObj;
JSONArray jsonArray = new JSONArray();
jsonArray.put(myJSONObj);
xmlJSONObj.put(obj, jsonArray);
}
else if ( myObj instanceof String || myObj instanceof Integer )
{
// if exist but is a primitive entry (like in your case), I force it to a "primitive" JSONArray
JSONArray jsonArray = new JSONArray();
jsonArray.put(myObj);
xmlJSONObj.put(obj, jsonArray);
}
}
Hope this could help ;)
Based on Mario's solution, I made some changes, specially for nested children in the Json object. The xmlJSONObj is the same, but the obj param is a List that contains the path to the JSON child, and the index param is only required for the recursion (it should start at 0 in the first execution).
/**
* Forces a JSON Object to be an Array. When converting from XML to JSON, There may be cases in
* which we want a list of elements in the final JSON but there is only one element in the XML
* file, so the XML.toJSONObject method will fail. This methods forces a JSON element to be an
* array instead of just a JSON Object.
*
* @param xmlJSONObj obtained by passing the XML through the method toJSONObject
* @param obj list of String that contains the path to the JSON child to convert to Array
* @param index required for recursion, starts at 0
* @throws org.json.JSONException
*/
public static void forceToJSONArray(JSONObject xmlJSONObj, List<String> obj, int index)
throws org.json.JSONException {
Object myObj = xmlJSONObj.opt(obj.get(index));
if (myObj instanceof JSONObject && obj.size() == index + 1) {
JSONObject myJSONObj = (JSONObject) myObj;
JSONArray jsonArray = new JSONArray();
jsonArray.add(myJSONObj);
xmlJSONObj.put(obj.get(index), jsonArray);
} else if (myObj instanceof JSONObject) {
forceToJSONArray((JSONObject) myObj, obj, index + 1);
}
}
Example:
We have this JSON:
{
"person":{
"name":"Tony",
"data":{
"car":"Toyota"
}
}
}
And we want this JSON:
{
"person":{
"name":"Tony",
"data":{
"car":["Toyota"]
}
}
}
We should call the method like this:
forceToJSONArray(xmlJSONObj, Arrays.asList("person", "data", "car"), 0);