These docs are for v20.3.44. Click to read the latest docs for v20.3.186.

Discussions

Ask a Question
Back to All

Issue with Serialize and Deserialize the <MonetaryAmountData>.

Hi,

I tried to use Json.Net to deserialize the result from the API call, I got the following error:

"Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'Asi.Soa.Core.DataContracts.MonetaryAmountData' because the type requires a JSON primitive value (e.g. string, number, boolean, null) to deserialize correctly.
To fix this error either change the JSON to a JSON primitive value (e.g. string, number, boolean, null) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

You could see the same error with this test:
string testString = "{ "$type":"System.Nullable`1[[Asi.Soa.Core.DataContracts.MonetaryAmountData, Asi.Contracts]], mscorlib", "Amount":345.0, "Currency":{ "$type":"Asi.Soa.Core.DataContracts.CurrencyData, Asi.Contracts", "CurrencyCode":"AUD", "DecimalPositions":2, "ExtensionData":{ "$type":"System.Runtime.Serialization.ExtensionDataObject, System.Runtime.Serialization" } }, "IsAmountDefined":true }";

MonetaryAmountData test = JsonConvert.DeserializeObject(testString, settings);

It seems that it asks for a primitive string instead of a JSON string. Then, I tried to serialize a MonetaryAmountData object and got "345". And the error became "Newtonsoft.Json.JsonSerializationException: 'Error converting value "345" to type 'Asi.Soa.Core.DataContracts.MonetaryAmountData'. " when to deserialize it, which meant it didn't accept the primitive string.

MonetaryAmountData testAmount = new MonetaryAmountData((decimal)345.0, new CurrencyData("AUD"));
// testAmount = {345.00}, the currency part was missing.
string testSerialize = JsonConvert.SerializeObject(testAmount, Formatting.Indented);
// testSerialize = "345", it was a primitive string.
MonetaryAmountData testDeserialize = JsonConvert.DeserializeObject(testSerialize);

Is there anything I am doing wrong? Anyone successfully deserialized JSON to object in ASP.NET?

Cheers,
Fred