How to convert JSON to XML or XML to JSON?
Yes. Using the JsonConvert class which contains helper methods for this precise purpose:
// To convert an XML node contained in string xml into a JSON string
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);
// To convert JSON text contained in string json into an XML node
XmlDocument doc = JsonConvert.DeserializeXmlNode(json);
Documentation here: Converting between JSON and XML with Json.NET
Converting from JSON to XML using c#
At first, I would hardly recommend that your API team provides a valid JSON object. Otherwise you will have to write a converter that does the job. The converter could look like this:
using System.Collections.Generic;
namespace Json
{
using System.IO;
using System.Xml.Serialization;
using Newtonsoft.Json.Linq;
class Program
{
static void Main(string[] args)
{
var converter = new Converter();
converter.Convert();
}
}
class Converter
{
public void Convert()
{
// your JSON string goes here
var jsonString = @"{""status"":""Error"",""errorMessages"":{ ""1001"":""Schema validation Error"", ""1953"":""Another error""}}";
// deconstruct the JSON
var jObject = JObject.Parse(jsonString);
var root = new Root { Status = jObject["status"].ToString(), ErrorMessages = new List<ErrorMessage>() };
foreach (var errorMessageJsonObject in jObject["errorMessages"])
{
var jProperty = (JProperty)errorMessageJsonObject;
var errorCode = System.Convert.ToInt16(jProperty.Name);
var errorDescription = jProperty.Value.ToString();
var errorMessage = new ErrorMessage() { ErrorCode = errorCode, ErrorDescription = errorDescription};
root.ErrorMessages.Add(errorMessage);
}
// serialize as XML
var xmlSerializer = new XmlSerializer(typeof(Root));
string xml;
using (StringWriter textWriter = new StringWriter())
{
xmlSerializer.Serialize(textWriter, root);
xml = textWriter.ToString();
}
}
}
public class Root
{
public string Status;
public List<ErrorMessage> ErrorMessages;
}
public class ErrorMessage
{
public int ErrorCode;
public string ErrorDescription;
}
}
With this, you will read the JSON, deconstruct it into a proper object and serialize it as XML.
Converting a JSON file to a specific XML format
One option is to use json-to-xml()
in XSLT 3.0.
You'll need an XSLT 3.0 processor; I used Saxon-HE 9.8 in my example below.
You can pass the JSON in as a param.
The results of json-to-xml()
will look something like this:
<map xmlns="http://www.w3.org/2005/xpath-functions">
<array key="playerStats">
<map>
<string key="jerseyNumber">23</string>
<number key="fgPercentage">60</number>
<string key="plusMinus">plus</string>
</map>
<map>
<string key="jerseyNumber">24</string>
<number key="fgPercentage">40</number>
<string key="plusMinus">minus</string>
</map>
</array>
</map>
You can process that XML to get your target XML.
Example...
Java
package so.test1;
import java.io.File;
import java.io.OutputStream;
import javax.xml.transform.stream.StreamSource;
import net.sf.saxon.s9api.XsltTransformer;
import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.QName;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.Serializer;
import net.sf.saxon.s9api.XdmAtomicValue;
import net.sf.saxon.s9api.XsltCompiler;
import net.sf.saxon.s9api.XsltExecutable;
/**
*
* @author dhaley
*
*/
public class SOTest1 {
public static void main(String[] args) throws SaxonApiException {
final String XSLT_PATH = "src/so/test1/test.xsl";
final String JSON = "{\"playerStats\": [\n" +
" {\"jerseyNumber\": \"23\", \"fgPercentage\": 60, \"plusMinus\": \"plus\"},\n" +
" {\"jerseyNumber\": \"24\", \"fgPercentage\": 40, \"plusMinus\": \"minus\"}\n" +
"]}";
OutputStream outputStream = System.out;
Processor processor = new Processor(false);
Serializer serializer = processor.newSerializer();
serializer.setOutputStream(outputStream);
XsltCompiler compiler = processor.newXsltCompiler();
XsltExecutable executable = compiler.compile(new StreamSource(new File(XSLT_PATH)));
XsltTransformer transformer = executable.load();
transformer.setInitialTemplate(new QName("init")); //<-- SET INITIAL TEMPLATE
transformer.setParameter(new QName("json"), new XdmAtomicValue(JSON)); //<-- PASS JSON IN AS PARAM
transformer.setDestination(serializer);
transformer.transform();
}
}
XSLT 3.0 (test.xsl)
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xpath-default-namespace="http://www.w3.org/2005/xpath-functions">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:param name="json"/>
<xsl:mode on-no-match="shallow-copy"/>
<xsl:template name="init">
<!--Only process playerStats-->
<xsl:apply-templates select="json-to-xml($json)//array[@key='playerStats']"/>
</xsl:template>
<xsl:template match="array">
<BallerStats>
<xsl:apply-templates/>
</BallerStats>
</xsl:template>
<xsl:template match="map">
<BallerStat>
<xsl:apply-templates/>
</BallerStat>
</xsl:template>
<xsl:template match="*[@key='jerseyNumber']">
<Baller>
<BallerJersey xsl:expand-text="true">{.}</BallerJersey>
<Type>Jersey</Type>
</Baller>
</xsl:template>
<xsl:template match="*[@key='fgPercentage']">
<fgPercentage>
<Type>PERCENT</Type>
<Value xsl:expand-text="true">{.}</Value>
</fgPercentage>
</xsl:template>
<xsl:template match="*[@key=('plusMinus')]"/>
</xsl:stylesheet>
Output (stdout)
<?xml version="1.0" encoding="UTF-8"?>
<BallerStats>
<BallerStat>
<Baller>
<BallerJersey>23</BallerJersey>
<Type>Jersey</Type>
</Baller>
<fgPercentage>
<Type>PERCENT</Type>
<Value>60</Value>
</fgPercentage>
</BallerStat>
<BallerStat>
<Baller>
<BallerJersey>24</BallerJersey>
<Type>Jersey</Type>
</Baller>
<fgPercentage>
<Type>PERCENT</Type>
<Value>40</Value>
</fgPercentage>
</BallerStat>
</BallerStats>
C# convert JSON object to XML dynamically
Not building on your current code, you can take a look at this question
Using this one-liner:
XmlDocument doc = JsonConvert.DeserializeXmlNode("{\"Row\":" + json + "}", "root"); // JSON needs to be an object
You can end up with:
<root>
<Row>
<value>50</value>
<name>desired_gross_margin</name>
<type>int</type>
</Row>
<Row>
<value>50</value>
<name>desired_adjusted_gross_margin</name>
<type>int</type>
</Row>
<Row>
<value>0</value>
<name>target_electricity_tariff_unit_charge</name>
<type>decimal</type>
</Row>
<Row>
<value>0</value>
<name>target_electricity_tariff_standing_charge</name>
<type>decimal</type>
</Row>
<Row>
<value>0</value>
<name>target_gas_tariff_unit_charge</name>
<type>decimal</type>
</Row>
<Row>
<value>0</value>
<name>target_gas_tariff_standing_charge</name>
<type>decimal</type>
</Row>
<Row>
<value>10/10/2016</value>
<name>planned_go_live_date</name>
<type>DateTime</type>
</Row>
<Row>
<value>0</value>
<name>assumed_fuel_ratio</name>
<type>int</type>
</Row>
<Row>
<value>
<year_one>Cold</year_one>
<year_two>Average</year_two>
<year_three>Warm</year_three>
</value>
<name>weather_variable</name>
<type>string</type>
</Row>
</root>
Where json
is the input JSON on your question, it's close to what you want (which your post says is sort of okay), but if you want to go for your 1st and 2nd options, you can simply build new XML by manipulating this (renaming the nodes, etc.).
How to convert XML to JSON without attributes?
You can parse it with XDocument
. XDocument can remove attributes.
public static XDocument RemoveAttributes(string xml)
{
var xDoc = XDocument.Parse(xml);
xDoc.Document?
.Descendants()
.ForEach(x => {
foreach (var attr in x.Attributes().ToList())
{
if (attr.IsNamespaceDeclaration)
continue;
attr.Remove();
}
}
);
return xDoc;
}
var xDoc = RemoveAttributes(xmlString);
var json = JsonConvert.SerializeXNode(xDoc);
var jObject = JObject.Parse(json);
var final = Convert.ToString(jObject["SOAP-ENV:Envelope"]["SOAP-ENV:Body"]["Results"]);
Result is:
{
"Summary": {
"Status": "true",
"etc": "etc"
}
}
Converting JSON to XML in Java
Use the (excellent) JSON-Java library from json.org then
JSONObject json = new JSONObject(str);
String xml = XML.toString(json);
toString
can take a second argument to provide the name of the XML root node.
This library is also able to convert XML to JSON using XML.toJSONObject(java.lang.String string)
Check the Javadoc
Link to the the github repository
POM
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160212</version>
</dependency>
original post updated with new links
Related Topics
How to Obtain the Frequencies of Each Value in an Fft
Retrieving Property Name from Lambda Expression
Using Setwindowpos With Multiple Monitors
How to Dynamically Create a Class
Is Using Random and Orderby a Good Shuffle Algorithm
How to Get All Child Controls of a Windows Forms Form of a Specific Type (Button/Textbox)
All Possible Array Initialization Syntaxes
Parse String to Datetime in C#
Should 'Using' Directives Be Inside or Outside the Namespace
How to Remove All Event Handlers from an Event
Sending Email Through Gmail Smtp Server With C#
Multiple Levels in MVC Custom Routing
Extension Method and Dynamic Object
There Is Already an Open Datareader Associated With This Command Which Must Be Closed First