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

时间:2016-01-29 14:16:12

标签: c# json datetime

我在C#中使用WEB API构建了一个简单的Web服务。

此Web服务可以接受带有DateTime字段的JSON。

这是我的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,

    }

}
]
}

这是方法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"));
}

现在的问题是这个。如果我尝试调用此Web服务,则无法正确读取时间戳。我在JSON中插入了这个日期时间:

  

“01/29/2016 14:27:30:200”

但是在c#方法中我读到了这个:

我该如何解决?

  

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

     

EDIT   这是我的课程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
        }
    }
}

这是我的转换器

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

2 个答案:

答案 0 :(得分:1)

我已用此代码解决了我的问题:

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;
}
}

在我的ImmaginiSecSoc类中,我插入了这个:

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

答案 1 :(得分:0)

如果您没有使用第三方库来解析json,则日期值必须采用Microsoft json日期格式。 Microsoft的Javascript序列化程序和DataContract序列化程序使用Microsoft {@ 1}}之类的Microsoft json日期格式,因此您必须以该格式将数据发布到API端点。

如果您将以下JSON数据发布到API端点,您将获得有效日期。

/Date(1224043200000)/

/日期(1224043200000)/等于15.10.2008 04:00:00

有关Microsoft json日期时间格式的有用链接; Scott HanselmanMSDN

PS:1224043200000是刻度线,因此您可以在客户端创建它。

希望这有助于解决您的问题