简体   繁体   English

如何在WebApi方法[c#]中从JSON读取DateTime

[英]How can read DateTime from JSON in WebApi method [c#]

I have build a simple Web Service with WEB API in C#. 我已经在C#中使用WEB API构建了一个简单的Web服务。

This web service can accept a JSON with also DateTime field. 此Web服务可以接受带有DateTime字段的JSON。

This is my Json: 这是我的杰森:

{
   "sensorId" : "sensoreDiProva",
   "values" :

[
    {
"image":"###base64data###",
"image_width": 100,
"image_height": 100,
"timestamp": "01/29/2016 14:27:30:200",
"type": "BLOB",
"rectangles": 
    {
        "n_rects": 2,

    }

}
]
}

This is the method c# 这是方法c#

 [HttpPost, Route("secsocdata")]
public HttpResponseMessage insertSecSocData(ImmaginiSecSoc u)
{
    List<int> listaIdInseriti = new List<int>();
    //se l oggetto non è vuoto, lo salvo sul database.
    if (u != null)
    {
    List<CAMERA_SEC_SOC_Rectangles> listaRettangoli = null;
    //ciclo la lista delle varie immagini contenuti nella richiesta
    foreach (WSOmniacare.Models.AAHome.ImmaginiSecSoc.ImmaginiSecSocDTO immagini in u.values)
    {
        var camera = new CAMERA_SEC_SOC
        {
        Image = GetBytes(immagini.image),
        image_height = immagini.image_height,
        image_width = immagini.image_width,
        timestamp = immagini.timestamp,//DateTime.ParseExact(immagini.timestamp, "MM/dd/yyyy hh:mm:ss:fff", CultureInfo.InvariantCulture),
        type = immagini.type,
        CAMERA_SEC_SOC_Rectangles = listaRettangoli,
        FileStateID = 0,
        LastChangeDate = DateTime.Now,
        CreationDate = DateTime.Now,
        //CreationUserID = "0",
        //LastChangeUserID = "0"//ricavare l'userid
        };


    }
    //TO DO

    }
    return Request.CreateResponse(HttpStatusCode.OK, new RCamera((short)status_code.Failure, "KO"));
}

Now the problem is this. 现在的问题是这个。 If I try to call this web service I can't read correctly the timestamp. 如果尝试调用此Web服务,则无法正确读取时间戳。 I insert this datetime in my JSON: 我将此日期时间插入JSON:

"01/29/2016 14:27:30:200" “ 2016年1月29日14:27:30:200”

but in c# method I read this: 但是在C#方法中,我读到以下内容:

How can I fixed it? 我该如何解决?

{01/01/0001 00:00:00} {01/01/0001 00:00:00}

EDIT This is my class ImmaginiSecSocDTO 编辑这是我的课程ImmaginiSecSocDTO

[DataContract]
    public class ImmaginiSecSoc 
    {
        [DataMember(Name = "sensorId")]
        public string sensorId { get; set; }


        [DataMember(Name = "values")]
        public IEnumerable<ImmaginiSecSocDTO> values { get; set; }

        [DataContract(Name = "ImmaginiSecSocDTO")]
        public class ImmaginiSecSocDTO
        {

            [DataMember(Name = "image")]
            public string image { get; set; }

            [DataMember(Name = "image_width")]
            public Decimal? image_width { get; set; }

            [DataMember(Name = "image_height")]
            public Decimal? image_height { get; set; }

            [JsonConverter(typeof(CustomDateTimeConverter))]
            [DataMember(Name = "timestamp")]
            public DateTime timestamp { get; set; }

        //to do
        }
    }
}

This is my converter 这是我的转换器

public class CustomDateTimeConverter : IsoDateTimeConverter
    {
        public CustomDateTimeConverter()
        {
            base.DateTimeFormat = "MM/dd/yyyy hh:mm:ss.fff";
        }
    }

I have fixed my question with this code: 我用以下代码解决了我的问题:

public class CustomDateTimeConverter : DateTimeConverterBase//IsoDateTimeConverter
{

/// <summary>
/// DateTime format
/// </summary>
private const string Format = "MM/dd/yyyy hh:mm:ss.fff";

/// <summary>
/// Writes value to JSON
/// </summary>
/// <param name="writer">JSON writer</param>
/// <param name="value">Value to be written</param>
/// <param name="serializer">JSON serializer</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
    writer.WriteValue(((DateTime)value).ToString(Format));
}

/// <summary>
/// Reads value from JSON
/// </summary>
/// <param name="reader">JSON reader</param>
/// <param name="objectType">Target type</param>
/// <param name="existingValue">Existing value</param>
/// <param name="serializer">JSON serialized</param>
/// <returns>Deserialized DateTime</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
    if (reader.Value == null)
    {
    return null;
    }

    var s = reader.Value.ToString();
    DateTime result;
    if (DateTime.TryParseExact(s, Format, CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
    {
    return result;
    }

    return DateTime.Now;
}
}

and in my ImmaginiSecSoc class, I have insert this: 在我的ImmaginiSecSoc类中,我插入了以下代码:

[JsonConverter(typeof(CustomDateTimeConverter))]
[DataMember(Name = "timestamp")]
public DateTime timestamp { get; set; }

If you are not using a 3rd party library to parse json, date value must be in Microsoft json date format. 如果您没有使用第三方库来解析json,则日期值必须为Microsoft json日期格式。 Microsoft's Javascript serializer and DataContract serializer uses Microsoft json date format like /Date(1224043200000)/ so you must post your data to your API endpoint in that format. Microsoft的Javascript序列化程序和DataContract序列化程序使用Microsoft json日期格式,例如/Date(1224043200000)/因此您必须以该格式将数据发布到API端点。

If you post the JSON data below to your API endpoint you will get a valid date. 如果将下面的JSON数据发布到API端点,则将获得一个有效日期。

{
    "sensorId": "sensoreDiProva",
    "values": [{
        "image": "###base64data###",
        "image_width": 100,
        "image_height": 100,
        "timestamp": "/Date(1224043200000)/",
        "type": "BLOB",
        "rectangles": {
            "n_rects": 2,

        }
    }]
}

/Date(1224043200000)/ equals to 15.10.2008 04:00:00 / Date(1224043200000)/等于15.10.2008 04:00:00

Useful links about Microsoft json datetime format; 有关Microsoft json日期时间格式的有用链接; Scott Hanselman , MSDN 斯科特Hanselman的MSDN

PS: 1224043200000 is ticks so you can create it in your client. PS:1224043200000是刻度线,因此您可以在客户端中创建它。

Hope this helps with your issue 希望这对您的问题有所帮助

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

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