简体   繁体   English

如何以JSON格式传递TimeSpan值?

[英]How to pass TimeSpan value in JSON format?

I use Fiddler to test my WCF Rest. 我用Fiddler来测试我的WCF Rest。 I always get 我总是得到

HTTP/1.1 400 Bad Request  

with this post value: 有这个帖子值:

{
    "session":{
        "Session":"088a688d-ea69-4264-9266-381e9e540d00",
        "LoginID":"testid",
        "Serial":"testserial"
    },
    "sub":[
        {
            "Type":0,
            "StartDate":"\/Date(1319731200000+0800)\/",
            "EndDate":"\/Date(1319731200000+0800)\/",
            "Duration":"12:12:12"
        }
    ]
}  

I get the error in 'Duration' value. 我在'持续时间'值中得到错误。 I've been searching on net but no luck at all. 我一直在网上搜索但没有运气。
I hope I'll find the answer here. 我希望我能在这里找到答案。 Thanks a lot! 非常感谢!

The simple approach is to parse the timespan as a string and converting to a TimeSpan using its static 'parse' routine. 简单的方法是将时间跨度解析为字符串,并使用其静态“解析”例程转换为TimeSpan。

With JSON and WCF you are relying on the JSON Serialiser to convert objects back and forth, unfortunately once you start 'moving' away from native object types, ie strings, numerics, and into specific object, it tends to choke unless you use the exact format. 使用JSON和WCF,您依靠JSON Serialiser来来回转换对象,不幸的是,一旦您开始“移动”远离本机对象类型(即字符串,数字和特定对象),除非您使用精确对象,否则它往往会窒息格式。

Personally, I've had no experience of passing Timespan's through the DataContractJsonSerializer what format is required, however this post will highlight the exact format along with whether it is possible 就个人而言,我没有通过DataContractJsonSerializer传递Timespan的经验,需要什么格式,但是这篇文章将突出显示确切的格式以及是否可能

What is the .NET type of "sub"? 什么是.NET类型的“子”? It looks like a collection or array type of some sort; 它看起来像某种类型的集合或数组类型; what is the type that .NET expects those elements to have? .NET期望这些元素具有什么类型? Does that type have the properties Type, StartDate, EndDate, and Duration? 该类型是否具有Type,StartDate,EndDate和Duration属性? Does it have any other properties that are marked with [IsRequiredAttribute] but not present? 它是否有任何标有[IsRequiredAttribute]但不存在的其他属性?

If you craft up a fresh DataContractJsonSerializer (type = TimeSpan), and try to deserialize just the string "12:12:12", what happens then? 如果你制作一个新的DataContractJsonSerializer(type = TimeSpan),并尝试反序列化字符串“12:12:12”,那么会发生什么呢?

I am not giving you an answer yet -- but I think doing these exercises should not solve your problem now, but it will also help diagnose future errors you may encounter in the deserialization of this string. 我还没有给你答案 - 但我认为做这些练习现在不能解决你的问题,但它也有助于诊断你在反序列化这个字符串时可能遇到的未来错误。

See also Deserialize array values to .NET properties using DataContractJsonSerializer for some pointers 另请参阅使用DataContractJsonSerializer将数组值反序列化为.NET属性以获取一些指针

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM