we are trying to serialize a JSON object [as a string] into a custom class. While we rather not use any third-party packages such as Newtonsoft.Json or Json.NET, we tried to utilize DataContractJsonSerializer. The JSON object contains a DateTime property that is provided in the "yyyy-MM-dd HH:mm:ss" and when it comes to serialization the expectation below is thrown.
There was an error deserializing the object of type DateTime content '2020-05-29 09:05:39' does not start with '\/Date(' and end with ')\/' as required for JSON
IMPORTANT: the issue will be solved with NewtonSoft package and adding JsonSerializerSettings to JsonConvert.DeserializeObject. As the final product is is a COM Object, our final target dll must have no dependant DLLs.
You can find the technical details below:
JSON object is :
{
...,
"export_time": "2020-05-29 09:05:39",
"app_version": "1.1.0",
"allowed_mac_addresses": [
"XX-XX-XX-XX-XX-XX"
],
"signature": ""
}
Target class:
[DataContract]
public class MainFractionatorConfigFile
{
[DataMember]
internal string[] allowed_mac_addresses;
[DataMember]
internal DateTime export_time;
[DataMember]
internal string app_version;
[DataMember]
internal string signature;
}
and the serializer method is :
public static MainFractionatorConfigFile ReadMainFractionatorConfigFile(string json)
{
var deserializedUser = new MainFractionatorConfigFile();
var ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
var ser = new DataContractJsonSerializer(deserializedUser.GetType());
deserializedUser = ser.ReadObject(ms) as MainFractionatorConfigFile;
ms.Close();
return deserializedUser;
}
Attempt 1: There are some other suggestions in the community such as this solution but they demand other packages to be referenced.
Attempt 2 was trying to add DateTimeDataContractSurrogate to DataContractJsonSerializer but was unsuccessful too.
To sum up we are looking for an alternative method for the code below:
var mainFObj = JsonConvert.DeserializeObject<MainFractionatorConfigFile>(myJson, new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
});
Any help or idea will be appreciated.