Can I Deserialize a JSON string that contains 0.0 in C#? - 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

Related

Deserialize hexadecimal values with Newtonsoft JSON

I'm trying to deserialize json into a C# object. The json basically looks like this:
{ "hexValue": "0x9a7f" }
My POCO looks like this:
public class HexTest
{
public int hexValue;
}
I've read in a link from this question that Newtonsoft supports deserializing hex values. But in all fairness, those release notes were published a decade ago. I've even read in some source code on github
published here what appears to be code to deserialize a hex formatted string that starts with "0x". Yet, when I try to deserialize a hex value, I always get the following exception:
Could not convert string to int: 0x9a7f.
It doesn't matter what type I try. I've tried using int long decimal Decimal, etc... From reading the source it looked like the Decimal type should have worked but nothing works. Does Newtonsoft really have support for converting hex values defined as strings into a numeric data type of some kind?
Sure, I know I can use the information in the question I linked to above to implement custom support for it but I'd really rather use the built-in support if it's there.
Thanks to the comments to my original question above by Fildor, I was able to resolve the problem by removing quotes around the value in the JSON so it now read like this:
{ "hexValue": 0x9a7f }
Also, further testing reveals that any of the numeric data types work for this in the POCO including int, long, and decimal. It is probably worth noting that (not sure about the latest standard) most if not all JSON validators will consider this invalid JSON because hexadecimal is not a valid JSON numeric data type.
Taking another look at the source, it's clear why this works and not the string. The parser will only call the method that detects the 0x prefix if it recognizes the json value token as a numeric type which, if quoted, it cannot do because by definition, that is a string.

Characters added and wrong output during serialization with Json.NET

JSON.NET seems to serialize my code into what appear to be strings, instead of objects. Here's an example of what it returns:
"{\"kvk_nummer\":11111111,\"onderneming\":\"berijf B.V.\",\"vestigingsplaats\":\"AMSTERDAM\",\"actief\":1}"
It also adds strange backslashes, I tried to get rid of them, but none of the answers I've found seemed to have helped. Here is the code that returns the string.
getregister r = new getregister
{
kvk_nummer = col1, //contains an 8 digit number
onderneming = checkTotaal[col1], //contains a name
vestigingsplaats = checkTotaal2[col1], //contains a location
actief = 1 // bool that represents wether the company is active or not
};
yield return JsonConvert.SerializeObject(r);
How can i get JSON.NET to output an object, instead of some JSON strings?
Looks like you're confusing some stuff. Taken from Serialization (C#)
Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.
When you serialize into JSON, you get a JSON representation of your object. Which is a string representation. Taken from the JSON Wikipedia page:
JavaScript Object Notation or JSON is an open-standard file format that uses human-readable text to transmit data objects consisting of attribute–value pairs and array data types (or any other serializable value).
In short: your code is doing what you're asking it to do. As far as the slashes go: those are escape characters. If you want (JSON.NET to return) an object, return the object you're creating (r).
return new getregister
{
kvk_nummer = col1, //contains an 8 digit number
onderneming = checkTotaal[col1], //contains a name
vestigingsplaats = checkTotaal2[col1], //contains a location
actief = 1 // bool that represents wether the company is active or not
};
If you're looking for a way to have JSON.NET return an object, you should take a look into Deserializing it. Since that takes the string-representation (JSON) for your object, and turns it back into an actual object for you.

C# force integer when converting XML to JSON

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.

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!

Dynamic Json deserialization

Deserialize JSON into C# dynamic object?
Following above question, I copy the dynamicJsonDeserilization and trying to use that in my application.
then I try to access the object as
var Data = json.deserilization(jsonstring);
Now, my string is
{"0":{"Name":"C:\\","Type":"Partition","Path":"C:\\"},"1":{"Name":"D:\\","Type":"Partition","Path":"D:\\"},"2":{"Name":"E:\\","Type":"Partition","Path":"E:\\"}}
i.e. I just have an Array on my server which I convert to JSON string and send.
As per code from best answer I should be able to access it as Data.0 but it give "End of Expression expected", Also Data[0] is giving same error. I am not sure how can I use it ? Any help is appreciated. Thanks.
Now, my string is
{"0":{"Name":"C:\","Type":"Partition","Path":"C:\"},"1":{"Name":"D:\","Type":"Partition","Path":"D:\"},"2":{"Name":"E:\","Type":"Partition","Path":"E:\"}}
Your string is indeed not valid JSON due to escaped quotes.
Those C:\ are breaking the parser. You should generate it like this, sending three backslahes:
{"0":{"Name":"C:\\\","Type":"Partition","Path":"C:\\\"} ...

Categories