I have an XML string that does not contain a parent node. This XML is a representation of a json request for an API. It seems pointless, but it is done this way to make it easy for non programmers to read the file. In order to convert the XML to json, pretty much everything i have seen says to convert the string to an XMLDocument and then use the following to get the json.
string jsonText = JsonConvert.SerializeXmlNode(doc);
The problem i have here is that the xml is not really valid and because of this, it cannot be converted to an xml document. What i really want is to be able to do this.
string jsonText = JsonConvert.SerializeXmlNode(doc.InnerXml);
This doesnt work since innerXML is a string and not an object. I have been able to get it to work by creating a root element and then just using a sub string to cut the resulting string, but this seems pointless. There has to be a better way to do this without having to add xml only to have to remove it from the json afterwards. Is it possible to convert a piece of xml like the xml below into json like the example below.
<rootnode>
<fielda>a</fielda>
<fieldb>b</fieldb>
</rootnode>
Converts to
{
"fielda": "a",
"fieldb": "b"
}
There's an overload of SerializeXmlNode that takes a boolean omitRootObject:
string jsonText = JsonConvert.SerializeXmlNode(doc, Formatting.None, true);
JsonConvert.SerializeXmlNode has an overloaded method which you could use to ignore root.
string jsonText = JsonConvert.SerializeXmlNode(doc, Formatting.None, true);
Third parameter is for omitting RootObject
Related
var data = "{\"#access_token\":\"Vishnu\"}";
XmlDocument doc = (XmlDocument)Newtonsoft.Json.JsonConvert.DeserializeXmlNode(data.ToString(), "root", false, false);
var output = doc.InnerXml.ToString();
Expected output: <#access_token>Vishnu</#access_token>
but got : <_x0023_access_token>Vishnu</_x0023_access_token>.
public static XmlDocument DeserializeXmlNode(
string value,
string deserializeRootElementName,
bool writeArrayAttribute,
bool encodeSpecialCharacters --> both true and false gives same result.
)
Please give a method to get the # as it is XML.
Something that claims to convert JSON to XML can hopefully be relied upon to produce well-formed XML; it seems you want it to produce XML containing invalid characters in element names, which would not be useful to anyone.
Different JSON-to-XML converters have different ways of dealing with this problem, but at least if it's well formed XML you can then write an XSLT transformation to convert it to the XML you would like to see.
(If you want even more control over how the transformation is done, do the whole thing within an XSLT 3.0 stylesheet.)
I want to pass a filepath through JSON. On deserializing I am getting error:
Unrecognized escape sequence. (43): {"Jobtype": "StepBatch","SelectedId": "D:\Input\file1.CATPart"}
I have escaped characters but it still shows error...am I missing something here?
string json = "{\"Jobtype\": \"StepBatch\",\"SelectedId\": \"D:\\Input\\file1.CATPart\"}";
var jsonObj = new JavaScriptSerializer().Deserialize<List<Arguments>>(json);
The problem is that the content of your string at execution time is:
{"Jobtype": "StepBatch","SelectedId": "D:\Input\file1.CATPart"}
That's not valid JSON, because of the backslashes in the value for SelectedId. You'd need the JSON to be:
{"Jobtype": "StepBatch","SelectedId": "D:\\Input\\file1.CATPart"}
so your C# would have to be:
string json = "{\"Jobtype\": \"StepBatch\",\"SelectedId\": \"D:\\\\Input\\\\file1.CATPart\"}";
However, given that you're immediately deserializing the JSON anyway, I'd suggest getting rid of the JSON part entirely, and just creating the Arguments values yourself.
If you need to produce JSON, create the right values directly, and then get JavaScriptSerializer (or preferrably Json.NET) to create the JSON for you, instead of hand-coding it.
I am attempting to convert XML into JSON in order to generate a HTTP POST request to an API. I am getting an error because one of the fields is meant to be an integer instead of a string. From what i have read adding "json:Integer="true"" to the node will cause it to become an int, but this doesnt seem to be working for me. Here is the xml and the resulting json. The arrays are working, but the integer is not.
<shipments json:Array="true" xmlns:json="http://james.newtonking.com/projects/json">
<shipment_tracking_number />
<response_shipment_date>2016-10-18T01:00:00.0000000-04:00</response_shipment_date>
<response_shipment_method>UPS Ground</response_shipment_method>
<expected_delivery_date>2016-10-18T01:00:00.0000000-04:00</expected_delivery_date>
<ship_from_zip_code>12345</ship_from_zip_code>
<carrier_pick_up_date>2016-10-18T01:00:00.0000000-04:00</carrier_pick_up_date>
<carrier>UPS</carrier>
<shipment_items json:Array="true">
<shipment_item_id>FF12345K</shipment_item_id>
<alt_shipment_item_id>1234567890</alt_shipment_item_id>
<merchant_sku>B00xxxx</merchant_sku>
<response_shipment_sku_quantity json:Integer="true">1</response_shipment_sku_quantity>
</shipment_items>
</shipments>
string jsonrequest = JsonConvert.SerializeXmlNode(doc,
Newtonsoft.Json.Formatting.None, true);
{"shipments":[
{
"shipment_tracking_number":null,
"response_shipment_date":"2016-10-18T01:00:00.0000000-04:00",
"response_shipment_method":"UPS Ground",
"expected_delivery_date":"2016-10-18T01:00:00.0000000-04:00",
"ship_from_zip_code":"12345",
"carrier_pick_up_date":"2016-10-18T01:00:00.0000000-04:00",
"carrier":"UPS",
"shipment_items":[
{
"shipment_item_id":"FF12345K",
"alt_shipment_item_id":"1234567890",
"merchant_sku":"B00xxxx",
"response_shipment_sku_quantity":"1"
}]
}]
}
I need "response_shipment_sku_quantity":"1" to show up as "response_shipment_sku_quantity":1, but it doesnt seem to be working. I can modify the XML or the code that performs the conversion. I dont mind which as long as this can be done.
You define the attribute wrongly. This is how it should look like.
<response_shipment_sku_quantity json:Type='Integer'>1</response_shipment_sku_quantity>
EDIT:
Newtonsoft.Json XmlNodeConverter
Look methods private void SerializeNode and string dataType = GetDataType(node); they suggest this definition.
Another option is to Deserialize the xml to class with proper types for the properties and after that Serialize it to Json.
I am evaluating Json.Net.Schema from NewtonSoft and NJsonSchema from GitHub and I cannot figure out how to create a JSON schema from a JSON object. I want it to work exactly like this site does: http://jsonschema.net/#/
What I am looking for
string json = #"{""Name"": ""Bill"",""Age"": 51,""IsTall"": true}";
var jsonSchemaRepresentation = GetSchemaFromJsonObject(json);
I would expect a valid JSON schema in the jsonSchemaRepresentation variable. Does anyone know how I can accomplish this?
Thanks in advance!
The current version of NJsonSchema supports this feature:
The SampleJsonSchemaGenerator generates a JSON Schema from sample JSON data.
var schema = JsonSchema4.FromSampleJson("...");
var schemaJson = schema.ToJson();
... or create a SampleJsonSchemaGenerator instance and call the Generate("...") method.
Actually both of the libraries you mentioned do not support such a functionality.
If you're down to implement it yourself then you will have to parse your JSON, iterate over it recursively and add a new schema depending on the type of what you've just iterated over.
There are also some other tools (in other languages like python) which could be an inspiration, this might get you started.
The string you are submitting to the function is not in the correct format. Try this (add '{' to the start of the string, '}' to the end):
string json = #"{
""Name"": ""Bill"",
""Age"": 51,
""IsTall"": true
}";
var jsonSchemaRepresentation = GetSchemaFromJsonObject(json);
I have an xml string that I wish to traverse using LINQ to XML (I have never used this, so wish to learn). However when I try to use
XDocument xDoc = XDocument.Load(adminUsersXML);
var users = from result in xDoc.Descendants("Result")
select new
{
test = result.Element("USER_ID").Value
};
I get an error message saying illegal characters in path. reading up on it, it's because I cannot pass a standard string in this way. Is there a way to use XML LINQ qith a standard string?
Thanks.
My guess is that adminUsersXML is the XML itself rather than a path to a file containing XML. If that's the case, just use:
XDocument doc = XDocument.Parse(adminUsersXML);
As said in MSDN, you must use the Parse function to create a XDocument from a string.
I think adminUserXML is not a file but a string containing xml, which should be parsed to convert to XDocument with XDocument.Parse(adminUserXML)