newtonsoft json.net disable scientific notation - json.net

I would like my webapi to serialize json using camelcase. So i added the following to Global.asax.
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;
What i noticed is that because i set UseDataContractJsonSerializer to false, big decimals are serialized using scientific notation. How can i keep camelcase and at the same time disable scientific notation ?
Thanks

Related

Lowercase Property Names

I am adding a document to Cosmos DB with following line:
client.CreateDocumentAsync(collectionLink, report).Wait();
My c# classes are uppercase however standard json you lowercase properties. Is it possible somehow to ensure this when saving the document?
Some of the DocumentClient constructors accept an object called JsonSerializerSettings.
You can provide a different contract resolver there. In your case it's the CamelCasePropertyNamesContractResolver.
var client = new DocumentClient(new Uri(""), "", serializerSettings: new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});

EF 4.3 Json.Net 6.0.8 not taking programatic params in serialization

I'm using json.net for first time. It's really simple, but I have a problem: It seems to be JsonConvert.SerializeObject(Model, Formatting.Indented) should return no references and by using PreserveReferencesHandling = Ignore, it should dispose $id attributes as well, but I can't manage it.
My JsonConvert.SerializeObject call is in a razor view (MVC3) and JSON string I'm getting is
{"Items": [
{
"$id": \"1\",
"ID_DB": 18,
"ID_SAP": null,
...
}]
}
Perhaps, I need to change Web.config or put more config settings in another file(s) in my project. Please, can you tell me what I'm missing?
Thanks you all in advance.
Regards
Tistklehoff
Thanks for all your tips
Finally, I've just fix it:
I was working with EntityObject generator, so, my data was not in POCO models. But, if I change to DbContext generator, Json.Net haven't any problems serializing to JSON my new POCO objects.
Anyway, perhaps, any of you could tell me if I missed any code to work with 'EntityObject style'. I'll try your suggestions, it's a matter of pride now... ;)
My Json.Net code remains untouched between EO and DbC versions:
In DataView.cshtml, only this two lines:
JsonSerializerSettings config = new JsonSerializerSettings { MetadataPropertyHandling = MetadataPropertyHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, ContractResolver = new ExcludeEntityKeyContractResolver() };
string json = JsonConvert.SerializeObject(Model, Formatting.Indented, config);
Thanks a lot for your time.
Regards.
Tistklehoff.

Json.Net with [WebMethod]s

I'm trying to swap out the Json formatter to Json.Net, so I can get ISO dates instead of "/Date(1379112467317)/"
I'm also letting .Net (WebForms) auto-magically handle Json serialization/deserialization through [WebMethod]s. Which don't seem to be using the Json.Net formatter.
In my global.asax, I can see the old MS Json formatter getting removed, and the new Json.net formatter added with the IsoDateTimeConverter.
But, my [Webmethod]s still come back with the old /Date()/ json strings instead of Iso dates. Do I have to do anything special in my global.asax for [Webmethod]s auto-magic to use the new formatter?
Here's the code in global:
As seen in: http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx
var formatter = config.Formatters.Where(f => { return f.SupportedMediaTypes.Any(v => v.MediaType.Equals("application/json", StringComparison.CurrentCultureIgnoreCase)); }).FirstOrDefault();
if (formatter != null)
{
config.Formatters.Remove(formatter);
}
JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
serializerSettings.Converters.Add(new IsoDateTimeConverter());
config.Formatters.Add(new JsonNetFormatter(serializerSettings));
I think the way that you setup the formatter looks fine for me. but how do you make sure it is being use in the webform returns, it doesn't happen automatically.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Something GetSomething()
{
}
how about you try that.

How do I add a Dictionary<string,string> to an existing JSON.Net's JObject?

I've got a JObject (using JSON.Net) that I created by parsing some JSON text. I'm directly manipulating, adding keys at the top level of this JObject. I have no problems when the value I'm adding is a string:
json["newkey"] = "New Value"; // works
But I'll be damned if I can figure out how to add a Dictionary, e.g.:
Dictionary<string,string> dict = new Dictionary<string,string>();
dict["one"] = "1";
dict["two"] = "2";
json["dict"] = dict; // fails
I've done quite a bit of googling and reading the JSON.Net docs, but everything seems oriented towards reason JSON text into a JObject, or writing .NET objects as JSON text using serialization. Or using some fancy LINQ statements to do all kinds of things with complex objects...
I've tried these and none have worked:
json["dict"] = new JObject(dict);
json["dict"] = new JObject((Dictionary<string,string>)dict);
json["dict"] = new JArray(dict); // desperation sets in :)
json["dict"] = (JObject)dict; // please dear god let this work
Most of the latest errors I encounter are:
Could not determine JSON object type for type System.Collections.Generic.KeyValuePair`2[System.String,System.String].
I believe that you are looking for something like this:
json["dict"] = JObject.FromObject(dict);
There is a desperate "hack" that you can use, it's not pretty (doing twice the same thing) but it works :)
json["dict"] = JObject.Parse(JsonConvert.SerializeObject(dict));

How do I prevent Flash's URLRequest from escaping the url?

I load some XML from a servlet from my Flex application like this:
_loader = new URLLoader();
_loader.load(new URLRequest(_servletURL+"?do=load&id="+_id));
As you can imagine _servletURL is something like http://foo.bar/path/to/servlet
In some cases, this URL contains accented characters (long story). I pass the unescaped string to URLRequest, but it seems that flash escapes it and calls the escaped URL, which is invalid. Ideas?
My friend Luis figured it out:
You should use encodeURI does the UTF8URL encoding
http://livedocs.adobe.com/flex/3/langref/package.html#encodeURI()
but not unescape because it unescapes to ASCII see
http://livedocs.adobe.com/flex/3/langref/package.html#unescape()
I think that is where we are getting a %E9 in the URL instead of the expected %C3%A9.
http://www.w3schools.com/TAGS/ref_urlencode.asp
I'm not sure if this will be any different, but this is a cleaner way of achieving the same URLRequest:
var request:URLRequest = new URLRequest(_servletURL)
request.method = URLRequestMethod.GET;
var reqData:Object = new Object();
reqData.do = "load";
reqData.id = _id;
request.data = reqData;
_loader = new URLLoader(request);
From the livedocs: http://livedocs.adobe.com/flex/3/langref/flash/net/URLRequest.html
Creates a URLRequest object. If System.useCodePage is true, the request is encoded using the system code page, rather than Unicode. If System.useCodePage is false, the request is encoded using Unicode, rather than the system code page.
This page has more information: http://livedocs.adobe.com/flex/3/html/help.html?content=18_Client_System_Environment_3.html
but basically you just need to add this to a function that will be run before the URLRequest (I would probably put it in a creationComplete event)
System.useCodePage = false;

Resources