I'm using C# in a console app and I need a quick way to check if a string being returned from another service is XML or JSON.
I know if it was just XML, I could check it against a schema, or if it was just JSON I could try to parse it with JSON.Net, but is there a quicker way - maybe using build in .Net functions - just to tell which it is before then going on to process it?
Check the content type of the response message. You can also read the first character from the response. If it's a XML content, you should find a < . Even if the XML declaration is present or not.
You could try to parse the string into an XDocument. If it fails to parse, then you know that it is not valid. string xml = ""; XDocument document = XDocument. Parse(xml);
The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JSchema) method with the JSON Schema. To get validation error messages use the IsValid(JToken, JSchema, IList<String> ) or Validate(JToken, JSchema, SchemaValidationEventHandler) overloads.
Very simple:
I'm talking about non-space data.
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