-1

I have a class with a 'long' datatype. Using json.net to deserialize the web request containing this object (that is coming in through webapi).

Ex.

public class Employee{
long id,
string name
}

A request like the below deserializes correctly,

{"id":"123","name":"foo"}
(notice the double quotes around value of 'id')

But a request like the below fails to deserialize,

{"id":123,"name":"foo"}

I tried writing a custom JsonConverter and overriding the ReadJson method to convert value to Int64 but it hasn't helped.


Update: May be I oversimplified my question. Adding more detail. I encounter this when the type is used as a parameter in an odatacontroller's method

public class mycontroller : odatacontroller
{

[HttpPost]
public void Post([FromBody] Employee newEmp)
{
}
}

'null' is received for newEmp when the body is:

{"id":123,"name":"foo"}

I get a valid newEmp object for body like:

{"id":"123","name":"foo"} or
{"name":"foo"} (ie, when id is excluded)

user1198407
  • 381
  • 3
  • 16
  • I tried your JSON (with `"id":123`) with a stock call to `JsonConvert.DeserializeObject` where `Foo` is a class defining a `long` `Id` property, and a `string` `Name` property. It worked fine. Please post a self-contained compilable exmaple demonstrating your problem. – Kirk Woll Aug 12 '14 at 01:48
  • Hi, updated the question. It is in the above context that I am not able to deserialize long types. – user1198407 Aug 12 '14 at 21:19

2 Answers2

2

It looks like this is by design. The following error is reported when I dig into the modelstate's error dictionary.

Primitive values of type 'Edm.Decimal' and 'Edm.Int64' must be quoted in the payload. Make sure the value is quoted

According to the following SO thread, this is odata json's behavior.

WinJS OData JSON

Community
  • 1
  • 1
user1198407
  • 381
  • 3
  • 16
1

You should be getting a long as it is, json.net assumes that all int types are Int64. Here a comment by the author of json.net in response to somebody asking for an Int32:

Json.NET by default reads integer values as Int64 because there is no way to know whether the value should be Int32 or Int64, and Int64 is less likely to overflow. For a typed property the deserializer knows to convert the Int64 to a Int32 but because your property is untyped you are getting an Int64.

Justin R.
  • 23,435
  • 23
  • 108
  • 157