Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to quickly check if string is XML or JSON in C#

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?

like image 699
finoutlook Avatar asked Aug 31 '11 11:08

finoutlook


People also ask

How do you know if a response is XML or JSON?

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.

How check string is XML or not in C#?

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);

How check response is JSON or not in C#?

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.


1 Answers

Very simple:

  1. Valid JSON starts always with '{' or '['
  2. Valid XML starts always with '<'

I'm talking about non-space data.

like image 163
Artyom Avatar answered Sep 19 '22 14:09

Artyom