newtonsoft Serialize XML attributes issues - c#

I am Serializing XML document with the help of json.net..
Some of the XML elements have attributes, so when i use:
JsonConvert.SerializeXNode(xml, Newtonsoft.Json.Formatting.None, true);
The XML element <shipmentIndex Name="items">0</shipmentIndex>
transform to that JSON:
{"shipmentIndex":{"#Name":"items","#text":"0"}
I am sending this JSON to an API that expect something like that:
{"shipmentIndex":0}
How can i send to the API the correct data?
i used the attributes for formatting the JSON according to the API demands.

If your xml variable is of type XElement, you can try to use it's RemoveAttributes method:
var cleanXML = xml;
cleanXML.RemoveAttributes();
JsonConvert.SerializeXNode(cleanXML, Newtonsoft.Json.Formatting.None, true);

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

Is it possible to extract the JSON schema from a JSON string?

I have a bunch of JSON strings, and would like to identify the schema of each one. This will allow me to keep a count of the different types of JSON objects in my collection of JSON strings.
I do not know the structure of these JSON strings ahead of time, and thus do not have a PONO to try to deserialize to.
I am currently using json.net, but am open to other options.
You could also use NJsonSchema for that,
see https://github.com/RSuter/NJsonSchema/wiki/SampleJsonSchemaGenerator
Previously JSchema was in JSON.NET Library but now its deprecated and they moved it to another library .. You Can Use Json.NET Schema ..It will easily Give You Schema of Any JSON String..even You Can Parse any JSON Using this Lib. ..like Suppose You Have JSON String ie _strJSON
JSchema schema = JSchema.Parse(_strJSON);

Prettify JSON before storing to TXT

I'm trying to figure out how to prettify when the JavaScriptSerializer serializes my custom object to json.
string json = _jsonSerializer.Serialize(listToSerializeToJson);
it is just one long string right now, not formatted.
I don't see an option for that on the built-in JavaScriptSerializer class. However, if you're using Json.Net you can do this.
string json=JsonConvert.Serialize(listToSerializeToJson, Formatting.Indented);
According to Json.Net's project page, JavaScriptSerializer and DataContractJsonSerializer do not support creating indented prettified JSON strings.
If it's just for testing/human readability, I like using Json Lint: http://jsonlint.com/.

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