Reputation: 1276
I have the following JSON being sent to an MVC controller:
{
"CId": 374,
"CultureId": 1,
"VGS": null,
"DisplayOrder": 1
}
I am using JSON.Net to convert this to a dynamic object and later assigning the properties into an entity:
public partial class FooEntity
{
public short DisplayOrder { get; set; }
public Nullable<short> VGS { get; set; }
public short CId { get; set; }
public short CultureId { get; set; }
}
Notice that the VGS property we are assigning into is a nullable short, however when trying to create a new instance of the entity and assign the values, I get an error when trying to assign the VGS:
dynamic data = JsonConvert.DeserializeObject(payload);
var foo = new FooEntity();
foo.CId = data.CId;
foo.CultureId = data.CultureId;
foo.VGS = data.VGS; // Errors here
foo.DisplayOrder = data.DisplayOrder;
An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code
Additional information: Input string was not in a correct format.
As far as I can tell, the json is correct to deserialize into a null value, and since I am assigning into a nullable value, I'm not sure what is causing the error?
Upvotes: 2
Views: 507
Reputation: 10851
JSON.Net does not know what to parse VGS
to, which will make it an object
. Then you cannot assign an object
to VGS
. Below is a working example. It can be solved in several ways:
Solution 1: Use explicit cast.
var payload = "{\"CId\": 374, \"CultureId\": 1,\"VGS\": null,\"DisplayOrder\": 1}";
dynamic dyn = JsonConvert.DeserializeObject<FooEntity>(payload);
var foo2 = new FooEntity();
foo.CId = dyn.CId;
foo.CultureId = dyn.CultureId;
foo.VGS = (short?)dyn.VGS; // Note the explicit cast.
foo.DisplayOrder = dyn.DisplayOrder;
Solution 2: Specify type.
var payload = "{\"CId\": 374, \"CultureId\": 1,\"VGS\": null,\"DisplayOrder\": 1}";
dynamic data = JsonConvert.DeserializeObject<FooEntity>(payload); // Specify type.
var foo = new FooEntity();
foo.CId = data.CId;
foo.CultureId = data.CultureId;
foo.VGS = data.VGS;
foo.DisplayOrder = data.DisplayOrder;
But then there's really no reason to use dynamic
at all. You can serialize it directly to the entity you want.
FooEntity entity = JsonConvert.DeserializeObject<FooEntity>(payload);
Upvotes: 1