JavaScriptSerializer value for i=3? - c#

JavaScriptSerializer oSerializer = new JavaScriptSerializer();
object i = 3;
string sJSON = oSerializer.Serialize(i); //"3"
The JavaScriptSerializer should serialize its parameter to JSON!
And the result is "3" ( which is not JSON)
What am I missing?
edit
Ive written a mail to douglas crockford
3 is not a json object/text but json value.
so i think msdn should clarify the serialize method.
http://i.stack.imgur.com/VOh3X.png

As has been said many times by different people, the output you are receiving is valid JSON.
From the JSON Specification (the Introduction):
JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays).
and further (Section 2.1):
A JSON value MUST be an object, array, number, or string, or one of the following three literal names:
false null true
My interpretation of specification tells me that the case you describe here is more a JSON value than a JSON object.

You asked it to serialise the value 3, and it did. That's exactly correct.
To be explicit: what exactly are you expecting to come out? JSON gives name-value pairs. The value "3" has no name, because the whole object is 3.
JSON is JavaScript object notation. Pass it an object, and you'll probably get what you're expecting.
You can use an anonymous type as M. Babcock suggests: new { i = 3 }.

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.

I have a json value in database ["20200"] in this format

,i need just 20200 value, how can I take this value? when try to take to a string its return a value like "[\"20200"]"
The squared brackets denote an array of values. You can use a JSON serialization library like NewtonSoft JSON to deserialize the data into an IEnumerable<string> and then take the first value:
var v = JsonConvert.DeserializeObject<IEnumerable<string>>("[\"20200\"]").FirstOrDefault();

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.

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

JSON string parsing issue in C#

The JSON string that I receive is inconsistent. Sometimes some of the data elements in the JSON return as 'List ' type, the other times return as 'dictionary' type. Currently using JavaScriptSerializer to Deserialize the JSON string, but it gives me an exception in the cases like
for example - I have a data field "jpjhseq" which I have declared as a dictionary but at times the JSON string returns this as a string and I get an exception. This issue happens for other fields as well.
JavaScriptSerializer serializer = new JavaScriptSerializer();
Foo foo = serializer.Deserialize<Foo>(jsonString);
Many a times I get following json string
{"element1":{"0":"0","1":"S","2":"S","3":"J","4":"Q","5":"X","6":"M"},"element2":{"1":"one" ,"2":"two","4":"four","5":"five","6":"six","7":"seven","8":"eight"}}
for other data i get following json string
{"element1":["0","S","S","J","Q","X","M"],"element2":["one" ,"two","four","five","six","seven","eight"]}
How can i write a generic json parser for such inconsistent json strings?
Key names will be standard, but the data type of their values may vary.
What can be done to resolve this issue?

Categories