Convert JSON String to XML string - c#

I have a JSON string as :
var jsonString = JSON.stringify(dataObject);
document.getElementById("hdnChromedata").value = jsonString;
==> hdnChromedata = JSON string
BUT in a different code section I am storing XML serialized string to "hdnChromedata" .as :
XmlSerializer xmlSerializer = new XmlSerializer(vinDescription.GetType());
StringWriter textWriter = new StringWriter();
xmlSerializer.Serialize(textWriter, vinDescription);
this.hdnChromedata.Value = textWriter.ToString();
==> hdnChromedata = XML string
AND while retriving the values I am deserializing the string like this :
XmlDocument doc = new XmlDocument();
doc.LoadXml(this.hdnChromedata.Value);
XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement);
XmlSerializer ser = new XmlSerializer(decodedInfo.GetType());
object textObj = ser.Deserialize(reader);
vinDescription = (AutoExact.AEVINDecoderService.VINDescription)textObj;
HERE the line doc.LoadXml(this.hdnChromedata.Value)
is throwing error when hdnChromedata is a JSON string.
My question is, HOW can I make this JSON String to XML string?
OR is there any other to address this?
Basically I need a method to convert JSON string to XML string in ASP.NET 1.1

You can use the Json.NET library's JsonConvert for that. See the specifics at http://james.newtonking.com/projects/json/help/index.html?topic=html/ConvertingJSONandXML.htm.
Json.NET is an open-source JSON handling library for .NET, and it's the best there is.

No need for conversion, just test the first character of the string before deserialising it. If the string starts with <, then treat it as XML, and if it starts with {, then treat it as JSON.

Use json-lib, a library which adds JSON support to any Java program. json-lib provides an XMLSerializer which can be used to output XML from a JSON object.
https://discursive.atlassian.net/wiki/display/CJCOOK/Converting+JSON+to+XML

Related

Json get array object from JSON Object C#

I have this json string passed to my webapi
string jsonstring = "{\"datamodel\": \"[{\"K1\":\"V1\",\"K2\":\"V2\"}]\"}";
I may have more than on pair of (K,V) inside. How do i parse this in C# ?
I thought i could first convert my string to a JObject and get the key for datamodel from that and then use JArray to parse the K,V. But its throwing a jsonreader exception on the first line of code here
JObject my_obj = JsonConvert.DeserializeObject<JObject>(jsonstring.ToString());
and then do this..
JObject data = my_obj["datamodel"].Value<JObject>();
First of all, the JSON string you are posting is not valid. Given your comment, you can clean up the quotes before and after the square brackets using this snippet:
string jsonstring = "{\"datamodel\": \"[{\"K1\":\"V1\",\"K2\":\"V2\"}]\"}";;
string jsonstringCleaned = jsonstring.Replace("\"[", "[").Replace("]\"", "]");
var my_obj = JsonConvert.DeserializeObject<JObject>(jsonstringCleaned);
The code is right, but the exception you are getting is related to the formatting of your JSON string. If you put valid JSON in this code, it should work as expected.
There are \" missing around V1 in your JSON string.
It should look like this:
string jsonstring = "{\"datamodel\": \"[{\"K1\":\"V1\",\"K2\":\"V2\"}]\"}";
First always make sure that you have a valid Json string. A simple way to do that is paste it into a Json to C# converter tool, such as this one: http://json2csharp.com/
It may be simpler and more readable to use single quotes within your Json string if that is an option, as it avoids the need to escape the double quotes:
string jsonstring = "{'datamodel': [{'K1':'V1','K2':'V2'}]}"
Now we deserialize the object and get the JArray. There is no need to call the ToString() on the JSON jsonstring string.
var my_obj = JsonConvert.DeserializeObject<JObject>(jsonstring);
var data = (JArray)my_obj["datamodel"];
A better and more concise way to accomplish the same result could be to just use JObject.Parse. We can accomplish the same result with just one line of code.
var data = (JArray)JObject.Parse(jsonstring)["datamodel"];

Deserialize json string that contains singlequote using c#

I have a json string that contains a string literal as value of one of the object - PostData.
string json = "{\"PostData\": '{\"LastName\": \"O Corner\",\"FirstName\":\"Mark\",\"Address\":\"123 James St\"}'}";
I am trying to deserialize the json using:
var obj = JsonConvert.DeserializeObject<dynamic>(json);
then, I can use my json string value of PostData like:
obj["PostData"].ToString()
But, as soon as I get the data with single quotes in it, like:
string json = "{\"PostData\": '{\"LastName\": \"O' Corner\",\"FirstName\":\"Mark\",\"Address\":\"123 James St\"}'}";
I get exception on deserialization. How can I escape the single quote?
I have checked SO for similar issues but didn't get any thing working. I also tried one of the solution mentioned int his thread:
JsonSerializerSettings settings = new JsonSerializerSettings
{
StringEscapeHandling = StringEscapeHandling.EscapeHtml
};
JsonConvert.SerializeObject(obj, settings);
But, I get Newtonsoft doesnot contain defination for StringEscapeHandling.
Also, tried to escape the singlequote with in the string with \:
'{\"LastName\": \"O\' Corner\",\"FirstName\":\"Mark\",\"Address\":\"123 James St\"}' which didn't work either.
For a start, it might be worth noting that the JSON syntax uses single quotes where you have used double quotes. Here is a guide for proper syntax:
Now unfortunately JSON does not allow the use of single quotes like that, but we can use the unicode \u0027 for an apostrophe and make use of JSON's serializer settings, as you have already done. So your original string:
string json = "{\"PostData\": '{\"LastName\": \"O' Corner\",\"FirstName\":\"Mark\",\"Address\":\"123 James St\"}'}";
becomes:
string json = "{'PostData': {'LastName': 'O\u0027 Corner','FirstName':'Mark','Address':'123 James St'}}"
This is assuming that you are parsing a string literal, otherwise you would need to escape the unicode to give:
string json = "{'PostData': {'LastName': 'O\\u0027 Corner','FirstName':'Mark','Address':'123 James St'}}"

XML String to JSON using only native .NET methods

I'm trying to rewrite a php function to C#. The php function converts an XML string to JSON.
At first, I came up with this:
string[] zips = { "27249","27215"}; // Request.Form.Get("zip").ToArray();
List<string> listings = new List<string>();
var webClient = new WebClient();
for (int i = 0; i != zips.Length; i++)
{
string returnXml = webClient.DownloadString("http://gateway.moviefone.com/movies/pox/closesttheaters.xml?zip=" + zips[i]);
var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(returnXml);
listings.Add(json);
Response.Write(json);
}
But the output included encoded characters, which wasn't what I wanted.
Then, using JSON.NET, I replaced the loop body with this:
string returnXml = webClient.DownloadString("http://gateway.moviefone.com/movies/pox/closesttheaters.xml?zip=" + zips[i]);
var xmlDoc = new System.Xml.XmlDocument();
xmlDoc.LoadXml(returnXml);
var json = JsonConvert.SerializeXmlNode(xmlDoc);
listings.Add(json);
What bothers me about this is thatthe conversion of the Xml string to an XmlDocument just so that I can convert it back to a JSON string seems unnecessary. I want the JSON string for later use in a jQuery function.
How can I make the first version work just using intrinsic .NET methods?
Thanks.
I can't tell you if there is a pre-made tool which does what you are looking for, but if you are looking to squeeze every bit of performance from this conversion, you can use JsonReader to read the JSON stream, and then use XmlWriter to output it to XML stream
With that said, if JSON you are getting comes from internet, you are unlikely going to significantly improve performance. But you are likely to introduce bugs. I would advice against that

Custom Json serialization

I have a list of KeyPairValue wich I serialize in Json Object using JavaScriptSerializer. The output of this operation give me something like this :
[{"Key":"A","Value":"ValueA"},{"Key":"D","Value":"ValueD"}]
I'ld like to get rid of those "" around the property name so it could look like this :
[{ Key:"A", Value:"ValueA"},{ Key:"D", Value:"ValueD"}]
Is there a way to achieve this or if what i'm looking for is just not a Json serialization ?
You can achieve it with Json.Net
StringWriter str = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(str);
writer.QuoteName = false; //<-- This is the trick
JsonSerializer jsonSer = new JsonSerializer();
jsonSer.Serialize(writer, new { ID = 1, Name = "Jack" });
string jsonstr = str.ToString();
Output is {ID:1,Name:"Jack"}
As I know it is a must requirement by JSON to embedd your keys in "". This is because JSON is actually a transport format for JavaScript objects and therefore it has some specifics.
The RFC specifies that a name is a string, and it also specifies that a string must be wrapped in quotation marks.
RFC 4627
It's worth noting the different types that values can be and that some of the types don't have to be wrapped in quotes. You can find this in the spec as well.

Error while deserializing XML from SQL Server

I have an application which serializes and deserializes .NET objects to XML. While deserializing I am getting the following error:
"There is an error in XML
Document(1,2) Name cannot begin with
the '.' character, hexadecimal value
0x00. Line 1, position 2. "
The code snippet that does the deserializing is:
string xmlEntity = _loanReader["LoanEntity"].ToString();
XmlSerializer xs2 = new XmlSerializer(typeof(Model.Loan));
MemoryStream memoryStream2 = new MemoryStream(StringFunction.StringToUTF16ByteArray(xmlEntity));
XmlTextWriter xmlTextWriter2 = new XmlTextWriter(memoryStream2, Encoding.Unicode);
_loan = (Model.Loan)xs2.Deserialize(memoryStream2);
I am using a datareader to get the resultset from the stored procedure. LoanEntity is an XML type field in the loan table.
A snippet of the XML stored in the field:
<Loan xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<GUID>d2cc9dc3-45b0-44bd-b9d2-6ef5e7ddb54c</GUID><LoanNumber>DEV999999</LoanNumber>
....
I have spent countless hours trying to figure out what the error means but to no avail. Any help will be appreciated.
This is usually an issue with encoding. I see you have the string bring converted to a UTF16 byte array. Have you checked that is should not be UTF8 instead? I would give that a go and see what comes of it. Basically the deserializer might be looking for a different encoding.
You must be working from an old example, and a bad one. Try this:
string xmlEntity = _loanReader["LoanEntity"].ToString();
XmlSerializer xs2 = new XmlSerializer(typeof(Model.Loan));
using (MemoryStream memoryStream2 = new MemoryStream(StringFunction.StringToUTF16ByteArray(xmlEntity)))
{
XmlWriterSettings settings = new XmlWriterSettings { Encoding = Encoding.Unicode};
using (XmlWriter writer = XmlWriter.Create(memoryStream2, settings))
{
_loan = (Model.Loan)xs2.Deserialize(memoryStream2);
}
}
I believe I may have found a solution to this. Since SQL Server XML field expects Unicode type encoding of values, I tried using a StringReader instead of a MemoryStream and things work well so far. The following StackOverFlow post helped as well:
Using StringWriter for XML Serialization

Categories