Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hook OData's $metadata response and convert it from XML to JSON

Tags:

The answer of Get OData $metadata in JSON format states that OData cannot return the metadata as JSON by default.

But is it possible then to capture or hook its response for the $metadata URL, and then convert it on the fly to JSON before sending it to the client?

I imagine pseudocode like this:

[HttpGet] [ODataRoute("$metadata")] public string GetMetadataAsJson() {     string xml = GetOdataMetadataAsXML();     string json = ConvertToJson(xml);     return json; } 

I don't know how to implement it correctly, though, in particular I'm not sure how to get the standard OData response as a string, and how to hook the $metadata URL.

like image 936
sashoalm Avatar asked Dec 16 '16 14:12

sashoalm


People also ask

Can we convert XML response to JSON?

To convert an XML document to JSON, follow these steps: Select the XML to JSON action from the Tools > JSON Tools menu. Choose or enter the Input URL of the XML document. Choose the path of the Output file that will contain the resulting JSON document.

Can we convert XML to JSON in JavaScript?

To convert XML text to JavaScript object, use xml2js() . To convert XML text to JSON text, use xml2json() .

What is $metadata in OData?

The OData $metadata file is a CSDL file that is made available to clients to help them discover the structure and organization of the entities, navigations, and the service operations that are available to manage resources beyond the usual create, retrieve, update, or delete operations.


1 Answers

Newtonsoft supports the Json part checkout https://www.newtonsoft.com/json/help/html/ConvertXmlToJson.htm

So the actual solution for the Json Part would be quite simple, as soon as you have your XML

[HttpGet] [ODataRoute("$metadata")] public string GetMetadataAsJson() {     string xml = GetOdataMetadataAsXML();     XmlDocument doc = new XmlDocument();     doc.LoadXml(xml);     string json = JsonConvert.SerializeXmlNode(doc);     return json; } 

Also you should probably first check if e.g. a format query is set for example with this code

[HttpGet] [ODataRoute("$metadata")] public string GetMetadataAsJson([FromQuery(Name="Format")]string format) {     string metaResult = GetOdataMetadataAsXML();     if(format.Equals("json",StringComparison.OrdinalIgnoreCase))     {         XmlDocument metaDoc = new XmlDocument();         doc.LoadXml(metaResult);         metaResult = JsonConvert.SerializeXmlNode(doc);     }     return metaResult; } 
like image 192
Fabian Kamp Avatar answered Sep 30 '22 17:09

Fabian Kamp