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?

2
  • Have a look here:stackoverflow.com/questions/21256132/… Commented Nov 7, 2014 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. Commented Nov 7, 2014 at 11:04

2 Answers 2

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); 
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

It is what i needed. i did not know how to add Convertor to JsonSerializer. Thanks...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.