1

I am using HTTPCLient to call RestFul service. My problem when parsing DateTime. Because in my class I have DateTime Property. Which in Json it is type long. Json key is: exp

{
  "resultCodes": "OK",
  "description": "OK",
  "pans": {
    "maskedPan": [
      {
        "id": "4b533683-bla-bla-3517",
        "pan": "67*********98",
        "exp": 1446321600000,
        "isDefault": true
      },
      {
        "id": "a3093f00-zurna-01e18a8d4d72",
        "pan": "57*********96",
        "exp": 1554058800000,
        "isDefault": false
      }
    ]
  }
}

In documentation i read that To minimize memory usage and the number of objects allocated Json.NET supports serializing and deserializing directly to a stream.

So =>

WAY 1 (Reading via GetStringAsync). In documentation has written that use StreamReader instead.

return Task.Factory.StartNew(() =>
            {
                var client = new HttpClient(_handler);    
                var url = String.Format(_baseUrl + @"list/{0}", sessionId);    
                BillsList result;    


                var rrrrr = client.GetStringAsync(url).Result;
                result = JsonConvert.DeserializeObject<BillsList>(rrrrr,
                                                   new MyDateTimeConverter());      


                return result;

            }, cancellationToken);

WAY 2(Good way. I read via StreamReader. Bu in line var rTS = sr.ReadToEnd(); it creates new string. It is not good. Because i have used GetStreamAsync to avoid of creating string variable.)

 return Task.Factory.StartNew(() =>
                {
                    var client = new HttpClient(_handler);    
                    var url = String.Format(_baseUrl + @"list/{0}", sessionId);    
                    BillsList result;    


                    using (var s = client.GetStreamAsync(url).Result)
                    using (var sr = new StreamReader(s))
                    using (JsonReader reader = new JsonTextReader(sr))
                    {  
                        var rTS = sr.ReadToEnd();
                        result = JsonConvert.DeserializeObject<BillsList>(rTS,
                                                  new MyDateTimeConverter()); 
                    }                     

                    return result;

                }, cancellationToken);

WAY 3(The best. But it gives exception if property is DateTime in my class. )

 return Task.Factory.StartNew(() =>
                {
                    var client = new HttpClient(_handler);    
                    var url = String.Format(_baseUrl + @"list/{0}", sessionId);    
                    BillsList result;    


                    using (var s = client.GetStreamAsync(url).Result)
                    using (var sr = new StreamReader(s))
                    using (JsonReader reader = new JsonTextReader(sr))
                    {  
                         var serializer = new JsonSerializer();                  
                         result = serializer.Deserialize<BillsList>(reader); 
                    }                     

                    return result;

                }, cancellationToken);

So my question. I want to continue with 3-rd way. But have there any way to set some handler as MyDateTimeConverter for JsonSerializer to convert it automatically?

AEMLoviji
  • 3,217
  • 9
  • 37
  • 61
  • Have a look here:http://stackoverflow.com/questions/21256132/deserializing-dates-with-dd-mm-yyyy-format-using-json-net – shrekDeep Nov 07 '14 at 10:46
  • Yes, but as you see this sample like my second sample. Where i do not want to create string object after reading it as Stream. – AEMLoviji Nov 07 '14 at 11:04

2 Answers2

3

You can set up default JsonSerializerSettings when your app is initialized:

        // This needs to be done only once, so put it in an appropriate static initializer.
        JsonConvert.DefaultSettings = () => new JsonSerializerSettings
        {
            Converters = new List<JsonConverter> { new MyDateTimeConverter() }
        };

Then later you can use JsonSerializer.CreateDefault

        JsonSerializer serializer = JsonSerializer.CreateDefault();
        result = serializer.Deserialize<BillsList>(reader); 
dbc
  • 104,963
  • 20
  • 228
  • 340
2

You can add your MyDateTimeConverter to the Converters collection on the JsonSerializer; that should allow you to use your third approach without getting errors.

    var serializer = new JsonSerializer();
    serializer.Converters.Add(new MyDateTimeConverter());
    result = serializer.Deserialize<BillsList>(reader);
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300