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

发布于 2024-11-09 05:42:43 字数 173 浏览 0 评论 0原文

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

Is there a universal way to instruct the DataContractJsonSerializer to use UTC for dates? Otherwise, I have to add .ToUniversalTime() to all of my date instances. Is this possible? The reason is that date values are defaulting DateTimeKind.Local and adding offsets to the JSON result. Making the dates universal does the trick, but can it be done at a global level? Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

丶情人眼里出诗心の 2024-11-16 05:42:43

没有办法直接在全局级别执行此操作 - 原始类型(例如 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()));
    }
}

There's no way to do that directly at the global level - primitive types (such as DateTime) can't be "surrogated". A possible workaround is to use some kind of reflection along with a surrogate to change the DateTime fields (or properties) in an object when it's being serialized, as shown in the example below.

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()));
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文