gpt4 book ai didi

c# - WCF DataContractJsonSerializer 并将 DateTime 对象设置为 UTC?

转载 作者:行者123 更新时间:2023-11-30 16:29:51 30 4
gpt4 key购买 nike

是否有一种通用的方法来指示 DataContractJsonSerializer 将 UTC 用于日期?否则,我必须将 .ToUniversalTime() 添加到我的所有日​​期实例中。这可能吗?原因是日期值默认 DateTimeKind.Local 并向 JSON 结果添加偏移量。将日期设置为通用日期可以解决问题,但它可以在全局范围内完成吗?谢谢。

最佳答案

无法在全局级别直接执行此操作 - 原始类型(例如 DateTime)无法“代理”。一种可能的解决方法是在序列化对象时使用某种反射和代理来更改对象中的 DateTime 字段(或属性),如下例所示。

public class StackOverflow_6100587_751090
{
public class MyType
{
public MyTypeWithDates d1;
public MyTypeWithDates d2;
}
public class MyTypeWithDates
{
public DateTime Start;
public DateTime End;
}
public class MySurrogate : IDataContractSurrogate
{
public object GetCustomDataToExport(Type clrType, Type dataContractType)
{
throw new NotImplementedException();
}

public object GetCustomDataToExport(MemberInfo memberInfo, Type dataContractType)
{
throw new NotImplementedException();
}

public Type GetDataContractType(Type type)
{
return type;
}

public object GetDeserializedObject(object obj, Type targetType)
{
return obj;
}

public void GetKnownCustomDataTypes(Collection<Type> customDataTypes)
{
}

public object GetObjectToSerialize(object obj, Type targetType)
{
return ReplaceLocalDateWithUTC(obj);
}

public Type GetReferencedTypeOnImport(string typeName, string typeNamespace, object customData)
{
throw new NotImplementedException();
}

public CodeTypeDeclaration ProcessImportedType(CodeTypeDeclaration typeDeclaration, CodeCompileUnit compileUnit)
{
throw new NotImplementedException();
}

private object ReplaceLocalDateWithUTC(object obj)
{
if (obj == null) return null;
Type objType = obj.GetType();
foreach (var field in objType.GetFields())
{
if (field.FieldType == typeof(DateTime))
{
DateTime fieldValue = (DateTime)field.GetValue(obj);
if (fieldValue.Kind != DateTimeKind.Utc)
{
field.SetValue(obj, fieldValue.ToUniversalTime());
}
}
}

return obj;
}
}
public static void Test()
{
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(MyType), null, int.MaxValue, true, new MySurrogate(), false);
MyType t = new MyType
{
d1 = new MyTypeWithDates { Start = DateTime.Now, End = DateTime.Now.AddMinutes(1) },
d2 = new MyTypeWithDates { Start = DateTime.Now.AddHours(1), End = DateTime.Now.AddHours(2) },
};
dcjs.WriteObject(ms, t);
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
}
}

关于c# - WCF DataContractJsonSerializer 并将 DateTime 对象设置为 UTC?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6100587/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com