Embedd xml in json - c#

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.

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

format dynamic json string from model for display in .net view

so I have a json string within my model data that is sent to the view for display in a table.
I am wanting to be sure it is displayed in a formatted fashion instead of one line string.
My research has led me to find this to be the cleanest method...
string json = JsonConvert.SerializeObject(account, Formatting.Indented);
however, within the view, once my value is extracted to #item.requestExample (the json string to be formatted), can I can call this c# to return the formatted string to the html?
btw, I've tried a few other methods just js, but every time the #item.requestExample is used within the , the inspect/console complains of the invalid tokens of the string since the string it an html representation that is using &quote; instead of "'s.
tia
Maybe you could parse the json (if it is json, I'm not sure I understood well) string into a dynamic object. Then you can iterate over the properties and visualize them at your will.
You can see how to do that here.
Deserialize JSON into C# dynamic object

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.

Pass string with Quote in Json result

I wanna send JSON response to browser that requested based on REST service. I use something like this that includes some quotes in Controller Method:
return Json("blah\"blah", JsonRequestBehavior.AllowGet);
And I expect the result would be blah"blah But is blah\"blah and includes back slash too! I wanna have blah"blah in response without any conversion in client side. I know that need to perform this via C# codes but how to do that?
C# and JSON encode characters similarly. The string blah"blah is encoded in both C# and JSON as "blah\"blah". It's perfectly expected, then, that your raw JSON includes the backslash.
When you decode that string with a proper JSON library, it again becomes the string blah"blah.
I found the answer in two above threads:
ASP.Net MVC: how to create a JsonResult based on raw Json Data
How to output Json string as JsonResult in MVC4?
So that I need to use something like this:
return Content(jsonStringFromSomewhere, "application/json");
With this in mind considering that JSONP is used in case of ajax requesting to external service or URL. But I wanna build specific string due to parse with a special parser and I used JSON rather than JSONP and result was great.

How to deserialize javascript objects to XML (not JSON) in 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#?

Categories

Resources