C# force integer when converting XML to JSON - c#

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.

Related

Can I Deserialize a JSON string that contains 0.0 in C#?

The JSON I'm getting back from a webservice has an integer incorrectly represented as 0.0. My deserialization code looks like this:
var serializer = new JsonSerializer();
var ret = serializer.Deserialize<T>(jsonTextReader);
And I get an error like this:
Input string '0.0' is not a valid integer.
My question is, is there a way to specify a less strict deserialization method so that I can parse this string?
EDIT: The web service returns no schema so I don't know why the deserializer tries to convert it to an int instead of a float or double.
I'd say that you should go ahead and creat your classes on Json -> C#
var o = (JObject)serializer.Deserialize(myjsondata);
You can use the C# dynamic type to make things easier. This technique also makes re-factoring simpler as it does not rely on magic-strings. Use JsonConvert.DeserializeObject<dynamic>()to deserialize this string into a dynamic type then simply access its properties in the usual way in C#.
Im not sure why youre getting
Input string '0.0' is not a valid integer.
since if you dont have any Json data it should just be left at null and you shouldnt have this problem

How to create json schema from json object string C#

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

How to deserialize in C# an unknown JSON string to some Object

I need to parse in C# (key ,value wise) a string that is built in a JSON format (to be exact I need to parse the binding parameter of Knockout data-bind).
I go over the html file and I extract the bindings. I want to modify each and every binding (string-wise), but It's really hard for me to parse the string, since I can't really know where each binding stops and the other starts.
for example:
data-bind="text:'ggggg',event:{mouseover:x=function(){alert(1);return 'd,y'}}"
will result in the following string:
"text:'ggggg',event:{mouseover:x=function(){alert(1);return 'd,y'}}"
I want to modify the string in the following way:
newString= "text('gggg'),event(mouseover(x=function(){alert(1);return 'd,y'}))"
I figured out that the best way to do it is to deserialize the string by JSON and then it will be easier for me to get access to each and every binding element.
I write at C#, but since I go over the html file and each data-bind is different and can contain different amount and type of attributes I would like to have a general object that I can deserialize to.
I checked out DataContractJsonSerializer but I don't see how it solves my problem.
Can you please suggest me what's best for my case?
Mary
You can do it with something like this:
var obj = ko.bindingProvider.instance.getBindings(yourDomElement,
ko.contextFor(yourDomElement));
alert(JSON.stringify(obj));
And then do whatever you want with obj.
Fiddle
But... well... don't!

Restsharp parsing names not supported by C# Json

Hi I'm making a web api client that returns stuff in json.
I'm using Restsharp that uses newtonsoft.json to deserialize json objects.
The problem is that the server returns an object with a property with #Text as name. Is there a way to make restsharp parse this?
Here is a sample:
image: [
{
#text: http://userserve-ak.last.fm/serve/34s/55125087.png
size: small
}]
All the other properties are being parsed just right the only problem is this one, the property is a string type so no problem in here.
Regards
That JSON isn't valid; you need to put quotes around the #text key (so make it "#text") as well as both values (so "http://...png" and "small").

How do I turn a C# Array to XML

I have a basic Generic List that I want turned into XML so I can return it to jquery. What I am trying to do is update my comments section in my article directory. I am returning an array of comment text, comment id, and user name. I would like to turn all of this into an array. Thanks
if (CommentFunctions.AddComment(aid, l.GetUserID(), id, comment))
{
//lets get all the comments for the article
List<CommentType> ct = CommentFunctions.GetCommentsByArticleID(id);
}
As others have pointed out, you'll need to serialize it to convert to XML.
I'd like to mention that if you're trying to return a list of objects to JQuery, that XML isn't the best or easiest format. Have you considered returning JSON?
JavaScriptSerializer serializer = new JavaScriptSerializer();
string JSONText = serializer.Serialize(List<CommentType>);
This will automatically create necessary json to describe your list of CommentTypes. JSON is much easier to parse in javascript and is much smaller to return via HTML.
Plus, you don't need to tell it your field names. It will find them for you and your JSON will be a list of classes just like your CommentType class.
You have to serialize it to XML. There are a number of ways to do this, more or less complex depending on the relative efficiency/speed you need, and the amount of control you need over the XML output.
Have a look here:
http://msdn.microsoft.com/en-us/library/ms950721.aspx
As Robert's comment mentions, you have to serialize the array to XML. Instead of retyping out the answer, however, I would recommend reading this blog post which discusses exactly how you would go about doing that.

Categories