English 中文(简体)
WCF DataContractJsonSerializer并将DateTime对象设置为UTC?
原标题:WCF DataContractJsonSerializer and setting DateTime objects to UTC?

是否有通用的方法来指示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()));
    }
}
问题回答

暂无回答




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Transaction handling with TransactionScope

I am implementing Transaction using TransactionScope with the help this MSDN article http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx I just want to confirm that is ...

System.Web.Mvc.Controller Initialize

i have the following base controller... public class BaseController : Controller { protected override void Initialize(System.Web.Routing.RequestContext requestContext) { if (...

Microsoft.Contracts namespace

For what it is necessary Microsoft.Contracts namespace in asp.net? I mean, in what cases I could write using Microsoft.Contracts;?

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签