1

I have build a simple Web Service with WEB API in C#.

This web service can accept a JSON with also DateTime field.

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#

 [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. I insert this datetime in my JSON:

"01/29/2016 14:27:30:200"

but in c# method I read this:

How can I fixed it?

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

EDIT This is my class 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";
        }
    }
7
  • I don't parsing JSON. If I try to inspect on immagini.timestamp I can't read the correct datetime Commented Jan 29, 2016 at 14:21
  • Sorry, I misunderstood the flow, and recognize now that it's the auto-parsing when your API method is called. Commented Jan 29, 2016 at 14:24
  • Are you running this just locally right now? What is the language setting on your machine? With all the ?Spanish? in your comments, it would make sense that your machine is looking for the date in a dd/MM/yyyy format, so 1/29/2016 is not a valid date, and would therefore parse to DateTime.MinValue. Commented Jan 29, 2016 at 14:26
  • What kind of API is that ? MVC Web Api ? WCF Rest API ? or else Commented Jan 29, 2016 at 14:26
  • The language of my Machine is Italian Commented Jan 29, 2016 at 14:30

2 Answers 2

1

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:

[JsonConverter(typeof(CustomDateTimeConverter))]
[DataMember(Name = "timestamp")]
public DateTime timestamp { get; set; }
Sign up to request clarification or add additional context in comments.

Comments

0

If you are not using a 3rd party library to parse json, date value must be in Microsoft json date format. 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.

If you post the JSON data below to your API endpoint you will get a valid date.

{
    "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

Useful links about Microsoft json datetime format; Scott Hanselman, MSDN

PS: 1224043200000 is ticks so you can create it in your client.

Hope this helps with your issue

2 Comments

I must pass date in this format "01/29/2016 14:27:30:200"
So you must implement your serialization provider which uses Newtonsoft or you have to send timestamp property as string then parse it into DateTime object. But personally if you have a chance to parse datetime before posting your data to your API endpoint its the best way, implementing a provider or posting datetime as string not worths.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.