我想将这样的对象序列化为JSON:
ConcreteClassA classA = GetContreteClassA();
var request = Helper.GetRestRequest("Insert", Method.POST);
request.JsonSerializer = new ConcreteClasseAJsonSerializer();
request.AddJsonBody(new { abClass = classA, useBasicProcess = true });
IRestResponse<AbstractClass> response = _restClient.Execute<AbstractClass>(request);
if (response.StatusCode != System.Net.HttpStatusCode.OK)
Helper.ThrowExeption(response);
使用此代码,我得到错误:
反序列化参数abClass时发生错误。 DateTime的内容不是以json期望的以'/ Date('开头,也不以')/'结尾。
这是此代码生成的JSON,并且"/Date("
属性没有DateMod
。
{"abClass":{"__type":"ConcreteClassA:http://www.test.com/WBS","Type":1,"Number":"FA8E5E78E70F04EB","Rate":7.85,"Name":"Toto",
"Qualite":"Société","DateMod":"0001-01-01T00:00:00"},"useBasicProcess":true}
以下是ConcreteClassAJsonSerializer
的Serialize方法的代码:
public string Serialize(object obj)
{
var binder = new ConcreteClassATypeNameSerializationBinder();
string jsonString = JsonConvert.SerializeObject(obj, Formatting.None, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects,
SerializationBinder = binder,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
});
jsonString = jsonString.Replace("\"$type\":\"\",", string.Empty);
jsonString = jsonString.Replace("$type", "__type");
return jsonString;
}
}
以及活页夹的BindToName方法的代码:
public void BindToName(Type serializedType, out string assemblyName, out string typeName)
{
if (serializedType == typeof(ConcreteClassA) || serializedType == typeof(ConcreteClassB) || serializedType == typeof(ConcreteClassC))
{
assemblyName = null;
typeName = serializedType.Name + ":" + TypeFormat;
return;
}
assemblyName = null;
typeName = null;
}
我必须使用此自定义序列化程序和活页夹,以便指定抽象类abClass
的具体类。
但是如何在序列化过程中添加缺少的\/Date(
?