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.
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.
To convert XML text to JavaScript object, use xml2js() . To convert XML text to JSON text, use xml2json() .
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With