Mark Nadig
Mark Nadig

Reputation: 5136

How can I get asp.net mvc to recognize decimals in json?

In my .net application I'm using System.Web.Mvc 5.2.3.0. My client is posting up json with the content-type: 'application/json'

{From: "EUR", To: "USD", Rate: 0.00001}

By the time my controller receives this

[HttpPut(), Route("/ExchangeRate/{exchkey}")]
public HttpResponseMessage PutCurrencyExchange(string exchkey, [FromBody()] JObject jsonData)
 {...

The JObject's Rate is a string "1E-05".

I've read about custom converters https://www.newtonsoft.com/json/help/html/N_Newtonsoft_Json_Converters.htm and contract resolvers https://www.newtonsoft.com/json/help/html/CustomContractResolver.htm

I found a number of very old examples for deserializing strongly typed objects. However, I'm hoping I'm just missing a simple configuration change that will allow my controller's JObject to correctly represent the decimal as a decimal. Note: I recognize that if the client stringifies the value, it will parse it correctly. However, I'm not able to dictate that consumers of my endpoints stringify the values first.

Upvotes: 0

Views: 382

Answers (1)

Patrick Goode
Patrick Goode

Reputation: 1452

I've had better luck with a controller action containing individual parameters rather than from body if you're able to change that

Upvotes: 1

Related Questions