How to deserialize javascript objects to XML (not JSON) in C#? - c#

I am using the following code to convert JSON string to XML for processing in C#:
XmlDictionaryReader xdr = JsonReaderWriterFactory.CreateJsonReader(System.Text.Encoding.Unicode.GetBytes(jsonStr), new XmlDictionaryReaderQuotas()); // ### QUOTA MAX WILL FIX THE MISSING CLOSING TAGS?
XElement root = XElement.Load(xdr); // Here I get the exception: The token '"' was expected but found '
I have used it with no problem until I tried to parse JSON with strings not enclosed by double quotes (which by the way, I think is perfectly fine with JSON format)
For example:
{string:"value"}
Can any body tell me how can I serialize JSON in C# so that this kind of simple format particulary wont break the code or generate exceptions?
EDIT:
I think what I am reading is not a JSON object but a javascript object like the following:
What's the difference between Javascript Object and JSON object
So question would be: How to deserialize javascript objects to XML (not JSON) in C#?

Related

Convert XML to JSON in C#

I have an XML and when converting to JSON, all the values became string as below:
XML:
<root><deviceToEgressLocationDistance>600</deviceToEgressLocationDistance></root>
JSON:
{ "deviceToEgressLocationDistance": "600" }
while it should be
JSON:
{ "deviceToEgressLocationDistance": 600 }
below the code I am using but it converts everything to strings
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlString);
string jsonContent = JsonConvert.SerializeXmlNode(doc, Formatting.Indented, true);
I have checked the solution in
Serialize Xml to Json using type attribute in c#
but I cannot manually parse every value as the xml file properties are changing every time so the next time it could be
XML:
<root><Location1>500.88</Location1><Location2>650</Location2></root>
The xml could have any structure including nesting properties.
Any ideas?
Update: After converting the XML to JSON, this JSON file is going to be the source to another system and if the JSON file has the wrong types like treating numbers as string or even DateTime as string, the subsystem fail to process the input source. So, I need to preserve the types in XML when converting to JSON

How to create a Xml Document from a fully escaped Xml string?

Question Background:
I have an XML response from a web service (that I am unable to control the content of) that I would like to validate. For example, often the response will have a URL in it that has query string parameters using a "&".
Code:
The following code gives an example of escaping an XML string with illegal characters. This will indeed produce an escaped string:
string xml = "<node>it's my \"node\" & i like it<node>";
string encodedXml = System.Security.SecurityElement.Escape(xml);
// RESULT: <node>it&apos;s my "node" & i like it<node>
If I know attempt to load this escaped XML into a new Xml Document, I will receive an error that the first character of the XML is not valid:
var doc = new XmlDocument();
// Error will occur here.
doc.LoadXml(encodedXml);
Error output:
Data at the root level is invalid. Line 1, position 1.
How do I load this escaped XML into an XML Document object?
This is not a valid XML document:
<node>it&apos;s my "node" & i like it<node>
When you escape the angle brackets on the tags, they are no longer treated as tags by the XML parser. It's all just text in an element -- but there's no element containing it. In XML, there must be a root element. That's a requirement. It may be an arbitrary requirement, and that may be unjust, but you'll never win an argument with a parser.
What you're doing is like giving this to a C# compiler:
string s = \"foo\" bar\";
The outer quotes shouldn't be escaped.
This is what you want:
string xml = "<node>it&apos;s my "node" & i like it</node>";
Note also that your original XML was broken already:
string xml = "<node>it's my \"node\" & i like it<node>";
Your "closing" tag isn't a closing tag. It should be </node>, not <node>.
If you are receiving a response from another web application / API / service, it is likely that the contents are Html encoded.
Take a look at the WebUtility class, particularly, HtmlDecode and UrlDecode. This is likely to convert your "string" data to proper Xml.
If you're receiving valid XML back from the service you can convert the response using something like this:
//...
WebResponse response = request.GetResponse();
XDocument doc = XDocument.Parse
((
new System.IO.StreamReader
(
response.GetResponseStream()
)
).ReadToEnd());
If you're receiving invalid XML from a service which should return valid XML, contact whoever owns/provides that service / raise a support ticket with them in the appropriate way.
Any other action is a hack. Sometimes that may be required (e.g. when you're dealing with a legacy system that's no longer supported with bugs that have never been corrected), but pursue the non-hacky routes first.

Deserializing JSON string into string array

I'm somehow having troubles deserializing a json string into a simple List or string[] (I don't care which).
As of what I know, this is how to do this job:
JsonConvert.DeserializeObject<List<string>>(jsonString);
Here I am getting a RuntimeBinderException. It complains about the parameter, although my json string is valid and simple: a:1:{i:0;s:10:"Sahibinden";}
What you have isn't JSON is a serialized PHP object. There have been some tools that work well with this in C# but there isn't native support. If you own the PHP, then convert the object/array to JSON first. If not try the information on this question: https://stackoverflow.com/a/1923626/474702
Your JSON is invalid. Problems:
a:1 should be inside an object bracket of {}
The : before the { is invalid, you need a , there
The ; just after i:0 is invalid, you need a comma there
You repeat the mistake described in 1. and 2. inside your {} brackets as well
Solution: You need to read about JSON and make sure you understand its syntax.

Embedd xml in json

I want to embed an xml string in a json string. I am returning this json from a web method and at client side I have to extract the xml string from this json data.
I tried this:
var data= $.parseJSON(jsonResponse);
But as the jsonResponse contains XML data it is becoming an invalid json and becomes unable to parse.
Is there any way to successfully embed xml string in json and extract it ?
EDIT:
Tried encoding xml string :
System.Security.SecurityElement.Escape(xmlString)
and then added it to json string.
Still at client side the json couldn't be parsed
EDIT
tried Ted Johnson's solution and the problem is partially fixed.
Now I could parse the json and extract the other attributes. But on accessing the xml attribute, it says undefined. Also couldn't decode it.
You will need to do the following.
Ensure the XML is encoded to project quote escaping. As the XML will need to be parsed as a string. In c# there is a standard way, URL Encoding using C#
ParseJSON
Access JSON attribute which has the xml encoded as a string and decode it. http://www.w3schools.com/jsref/jsref_decodeuri.asp
Parse the XML ... http://api.jquery.com/jQuery.parseXML/ and save result for use.

How to convert json from one format to another

I have a control that expects JSON in a particular format. I have a service that spits out JSON in a different format. What's the best way to convert the JSON to the expected format? C#, jQuery? I think I'd prefer to do it server-side.
With C# you can use System.Web.Script.Serialization.JavaScriptSerializer to parse your JSON string to an object or IDictionary.
MSDN: JavaScriptSerializer Class (System.Web.Script.Serialization)
With that object you could do anything you like, change values or maybe just parse it back to something like XML.

Categories

Resources