Thursday, February 27, 2014

RestSharp - using the Json.net serializer

On a recent project, it became apparent we had an issue when our date inputs started magically incrementing after a few saves by the user. We later found the culprit to be the serialization settings in the Rest Sharp C# library. The default RestSharp serializer was changing these DateTimes to adjust for UTC time against the server time, i.e. we would send '2-26-2014 : 4:49 PM' on the client and the RestSharp library would then translate this to '2-26-2014 9:49 PM" to adjust for UTC/GMT time. After several saves by the user you can probably guess what happens.

The fix for us ending up being avoiding the default RestSharp serializer and just reverting to use the Json.net serializer. You can do this by by overriding the request object's JsonSerializer property like so:


            var client = new RestClient("http://localhost:62104/");
            var request = new RestRequest("Product/card/margin", Method.POST);
            request.RequestFormat = DataFormat.Json;
            request.JsonSerializer = new RestSharpJsonNetSerializer();

You will of course need to define the custom Json.net serializer (shown below). The Rest Sharp team has provided this on their help page along with explanations about their move away from the Json.Net serializer.

https://github.com/restsharp/RestSharp/blob/master/readme.txt

You may lose some features of the RestSharp JsonSerializer, but if you are OK with that this approach should work great. Hopefully this helps someone else in the same boat!

            
using System.IO;
using Newtonsoft.Json;
using RestSharp.Serializers;

namespace MySerializerNamespace
{

    /// 
    /// Default JSON serializer for request bodies
    /// Doesn't currently use the SerializeAs attribute, defers to Newtonsoft's attributes
    /// 
    public class RestSharpJsonNetSerializer : ISerializer
    {
        private readonly Newtonsoft.Json.JsonSerializer _serializer;

        /// 
        /// Default serializer
        /// 
        public RestSharpJsonNetSerializer()
        {
            ContentType = "application/json";
            _serializer = new Newtonsoft.Json.JsonSerializer
            {
                MissingMemberHandling = MissingMemberHandling.Ignore,
                NullValueHandling = NullValueHandling.Include,
                DefaultValueHandling = DefaultValueHandling.Include
            };
        }

        /// 
        /// Default serializer with overload for allowing custom Json.NET settings
        /// 
        public RestSharpJsonNetSerializer(Newtonsoft.Json.JsonSerializer serializer)
        {
            ContentType = "application/json";
            _serializer = serializer;
        }

        /// 
        /// Serialize the object as JSON
        /// 
        /// Object to serialize
        /// JSON as String
        public string Serialize(object obj)
        {
            using (var stringWriter = new StringWriter())
            {
                using (var jsonTextWriter = new JsonTextWriter(stringWriter))
                {
                    jsonTextWriter.Formatting = Formatting.Indented;
                    jsonTextWriter.QuoteChar = '"';

                    _serializer.Serialize(jsonTextWriter, obj);

                    var result = stringWriter.ToString();
                    return result;
                }
            }
        }

        /// 
        /// Unused for JSON Serialization
        /// 
        public string DateFormat { get; set; }
        /// 
        /// Unused for JSON Serialization
        /// 
        public string RootElement { get; set; }
        /// 
        /// Unused for JSON Serialization
        /// 
        public string Namespace { get; set; }
        /// 
        /// Content type for serialized content
        /// 
        public string ContentType { get; set; }
    }
}

73 comments:

  1. One thing to add, you must actually register the serializer prior to calling AddBody. Interestingly, the serialization is actually done as part of the AddBody call, and not queued up and called as part of Execute.

    ReplyDelete
    Replies
    1. Thank you, your comment saved my sanity after 2+ hours of debugging! My serializer was not called and i was unable to find where the serialization occurs and was digging the wrong way...

      Delete
  2. Works like a charm! Thanks for doing this.

    ReplyDelete
  3. Are you trying to make money from your traffic by using popup advertisments?
    If so, did you take a look at PopCash?

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Attend The Python Training in Hyderabad From ExcelR. Practical Python Training Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python Training in Hyderabad.
    python training in bangalore

    ReplyDelete
  6. Very interesting, good job and thanks for sharing such a good blog. Your article is so convincing that I never stop myself to say something about it. You’re doing a great job. Keep it up. Plaese update for Machine Learning Training in Bangalore.

    ReplyDelete
  7. Business Analytics or Data Analytics or data science training in hyderabad is an extremely popular, in-demand profession which requires a professional to possess sound knowledge of analysing data in all dimensions and uncover the unseen truth coupled with logic and domain knowledge to impact the top-line (increase business) and bottom-line (increase revenue). ExcelR’s Data Science curriculum is meticulously designed and delivered matching the industry needs and considered to be the best in the industry.

    ReplyDelete
  8. Business Analytics or data science training in hyderabad is an extremely popular, in-demand profession which requires a professional to possess sound knowledge of analysing data in all dimensions and uncover the unseen truth coupled with logic and domain knowledge to impact the top-line (increase business) and bottom-line

    ReplyDelete
  9. We Innovate IT Solutions by offering end-to-end solutions for all of your IT challenges. Best IT Consulting Company In USA With one call or click, learn how we can help you with IT Consulting, IT Recruiting, Software Developers, Data Management and Mobile App Development. Regulus Technologies has been the trusted source for IT services to some of the most recognized companies in the North America. Learn how we can help you Innovate IT Solutions!

    ReplyDelete
  10. Attend The Course in Data Analytics From ExcelR. Practical Course in Data Analytics Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Course in Data Analytics.
    ExcelR Course in Data Analytics

    ReplyDelete
  11. At Regulus, all of our employees, whether full-time, leased, temporary or internal are just as important. Best IT Consulting Company In USA We’ll take the time to get to know you and understand your needs and requirements on an individual basis, and we’ll match your skills to our clients’ requirements. Our understanding and commitment to each individual employee and their goals is what you will get when you work with us.

    ReplyDelete
  12. latest Baby boy gentleman style

    Pattern Type: Cartoon
    Dresses Length: Above Knee, Mini
    Material Composition: Cotton
    Silhouette: A-Line
    Collar: Circular collar
    Sleeve Length(cm): Short
    Sleeve Style: REGULAR
    Style: Cute
    Material: COTTON
    Actual Images: yes
    Decoration: Flowers
    please visit

    ReplyDelete
  13. I have recently started a blog, the info you provide on this site has helped me greatly. Thanks for all of your time & work ExcelR Data Analytics Courses In Pune

    ReplyDelete
  14. Great post i must say and thanks for the information. Education is definitely a sticky subject. However, is still among the leading topics of our time. I appreciate your post and look forward to more. data science course

    ReplyDelete
  15. Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.
    digital marketing courses in Bangalore

    ReplyDelete
  16. It is extremely nice to see the greatest details presented in an easy and understanding manner..!. data science course Bangalore

    ReplyDelete
  17. I want to say thanks to you. I have bookmark your site for future updates. ExcelR Data Scientist Course Pune

    ReplyDelete
  18. After reading your article I was amazed. I know that you explain it very well. And I hope that other readers will also experience how I feel after reading your article.

    business analytics course

    data analytics courses

    data science interview questions

    data science course in mumbai

    For more info :

    ExcelR - Data Science, Data Analytics, Business Analytics Course Training in Mumbai

    304, 3rd Floor, Pratibha Building. Three Petrol pump, Opposite Manas Tower, LBS Rd, Pakhdi, Thane West, Thane, Maharashtra 400602
    18002122120

    ReplyDelete
  19. In this fashion my associate Wesley Virgin's report starts with this SHOCKING and controversial video.

    You see, Wesley was in the army-and soon after leaving-he unveiled hidden, "self mind control" tactics that the government and others used to get whatever they want.

    As it turns out, these are the EXACT same tactics many celebrities (especially those who "come out of nowhere") and top business people used to become rich and famous.

    You've heard that you use less than 10% of your brain.

    Really, that's because most of your brain's power is UNTAPPED.

    Maybe this expression has even taken place INSIDE your very own head... as it did in my good friend Wesley Virgin's head about 7 years back, while riding an unregistered, beat-up garbage bucket of a car without a driver's license and with $3 on his debit card.

    "I'm very fed up with living paycheck to paycheck! When will I finally succeed?"

    You've taken part in those questions, am I right?

    Your own success story is waiting to happen. All you have to do is in YOURSELF.

    Learn How To Become A MILLIONAIRE Fast

    ReplyDelete
  20. This is very educational content and written well for a change. It's nice to see that some people still understand how to write a quality post!
    Please check this Courses in Digital Marketing in Pune

    ReplyDelete
  21. I finally found great post here.I just added your blog to my bookmark sites. thanks.Quality posts is the crucial to invite the visitors to visit the web page, that's what this web page is providing.
    data science courses in pune

    ReplyDelete
  22. You might comment on the order system of the blog. You should chat it's splendid. Your blog audit would swell up your visitors. I was very pleased to find this site.I wanted to thank you for this great read!!
    machine learning course in pune

    ReplyDelete
  23. Very nice interesting blog found to be well written in a simple manner that everyone will understand and gain the enough knowledge from your blog being much informative is an added advantage for the users who are going through it. Once again nice blog keep it up.

    Artificial Intelligence course in chennai
    AI training in chennai
    AI course in Chennai
    Artificial Intelligence training in chennai

    ReplyDelete
  24. Very nice job... Thanks for sharing this amazing and educative blog post! ExcelR Courses In Digital Marketing In Pune

    ReplyDelete
  25. This is exactly the information I'm looking for, I couldn't have asked for a simpler read with great tips like this... Thanks! ExcelR Data Scientist Course In Pune

    ReplyDelete
  26. wonderful to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
    Correlation vs Covariance
    Simple linear regression
    data science interview questions

    ReplyDelete
  27. the fie Turing Test was devised. However this seems to indicate that machines can only become more intelligent as they become better able to simulate a single human's reasoning ability. artificial intelligence training in hyderabad

    ReplyDelete
  28. This is an excellent post I seen thanks to share it. It is really what I wanted to see hope in future you will continue for sharing such a excellent post.
    360digitmg ai courses

    ReplyDelete
  29. I have express a few of the articles on your website now, and I really like your style of blogging. I added it to my favorite’s blog site list and will be checking back soon…
    Machine Learning Courses in Pune I really enjoy reading and also appreciate your work.
    I have bookmarked your website because this site contains valuable information in it. I am really happy with articles quality and presentation. Thanks a lot for keeping great stuff. I am very much thankful for this site.

    ReplyDelete
  30. keep up the good work. this is an Ossam post. This is to helpful, i have read here all post. i am impressed. thank you. this is our site please visit to know more information
    data science training

    ReplyDelete
  31. Thanks for the Valuable information.Really useful information. Thank you so much for sharing. It will help everyone.

    SASVBA Delhi offers comprehensive ADVANCED EXCEL COURSE IN DELHI Extensive hands-on labs delivered by Excel and the Advanced Excel Institute in Delhi include live projects and simulations. Such detailed Excel and Advanced Excel courses have helped our students to get jobs in various multinational companies
    FOR MORE INFO:

    ReplyDelete
  32. Thanksfor the blog shared by you its amazing and helpful
    Data Science Training in Pune

    ReplyDelete
  33. Nice Blog !
    Here We are Specialist in Manufacturing of Movies, Gaming, Casual, Faux Leather Jackets, Coats And Vests See.Knights Varsity Jacket

    ReplyDelete
  34. This post is so interactive and informative.keep update more information...
    Hadoop Training in Bangalore
    Big Data Training in Bangalore

    ReplyDelete
  35. This comment has been removed by the author.

    ReplyDelete
  36. This comment has been removed by the author.

    ReplyDelete
  37. This comment has been removed by the author.

    ReplyDelete
  38. with Placement | 3RI Technologies
    data Analytics courses in pune
    3RI Technologies is the leading institution offering instructor-data analytics courses in pune Fresh graduates and working professionals can also enroll in it.
    data analytics Courses in Pune

    ReplyDelete
  39. This post is so helpfull and interavtive.Keep updating with more informaion...
    Salary Of Cyber Security
    Cyber Security Terms

    ReplyDelete
  40. Our the purpose is to share the reviews about the latest Jackets,Coats and Vests also share the related Movies,Gaming, Casual,Faux Leather and Leather materials available Rainbow Sunburst Jacket

    ReplyDelete
  41. I love to recommend you Where can crawl Exciting Products latest Jackets, Coats and Vests Click Here James Bond Black Jacket

    ReplyDelete
  42. Really impressed! Everything is very open and very clear clarification of issues. It contains truly facts. Your website is very valuable. Thanks for sharing.
    full stack developer course with placement

    ReplyDelete
  43. Nice blog and informative content to users. Thanks for sharing this information with us.
    Data Science Course Training in Hyderabad

    ReplyDelete
  44. I feel very grateful that I read this. It is very helpful and very informative and I really learned a lot from it.
    data science course in malaysia

    ReplyDelete
  45. I want you to thank for your time of this wonderful read!!! I definitely enjoy every little bit of it and I have you bookmarked to check out new stuff of your blog a must read blog!
    data analytics course in hyderabad

    ReplyDelete
  46. I am glad to be here and read your very interesting article, it was very informative and helpful information for me. keep it up. Tom Holland Uncharted Leather Jacket

    ReplyDelete
  47. Thanks for posting this info. I just want to let you know that I just check out your site and I find it very interesting and informative. I can't wait to read lots of your posts. data science training in kanpur

    ReplyDelete
  48. This comment has been removed by the author.

    ReplyDelete
  49. This is a very useful post for me. This will absolutely be going to help me in my project.
    full stack development course

    ReplyDelete
  50. Our Data Science certification training with a unique curriculum and methodology helps you to get placed in top-notch companies. Avail all the benefits and become a champion.
    data science courses in malaysia

    ReplyDelete
  51. Hi,
    Switching to the Json.net serializer in RestSharp is a smart move to tackle those date serialization issues. Your solution is well-explained and could save others from similar headaches. Thanks for sharing this valuable tip!
    Data Analytics Courses in Nashik

    ReplyDelete
  52. This article likely explains how to use the Json.NET serializer with RestSharp, offering insights into effective data serialization techniques in RESTful API communication.

    Data Analytics Courses In Kochi



    ReplyDelete
  53. "This article is very informative and answers all the questions I had about it perfectly."
    Mulesoft Course

    ReplyDelete
  54. This comment has been removed by the author.

    ReplyDelete
  55. "I found this blog post to be incredibly informative and engaging, and it perfectly captures the essence of the topic!"
    CCSP Course

    ReplyDelete
  56. Hey! your code examples are clear and well-explained, which is essential for understanding the implementation details. Thank you.
    Data Analytics Courses In Chennai

    ReplyDelete
  57. RestSharp, with the Json.net serializer, is a powerful combination for making API requests and handling JSON data in C#, simplifying data retrieval and manipulation in various applications. In the context of data analytics, Glasgow's Data Analytics courses offer hands-on training in working with data from various sources, making it easier to gather and analyze information from APIs and other data streams. Please also read Data Analytics courses in Glasgow.

    ReplyDelete
  58. Thanks for sharing valuable and informative blog post on RestSharp serializer.
    data analyst courses in limerick

    ReplyDelete

  59. "Your blog on using RestSharp with the Json.net serializer is a brilliant guide for developers seeking efficiency and clarity in API interactions. The integration of RestSharp and Json.net unlocks a powerful combination, and your step-by-step explanation ensures a smooth implementation. Thanks for shedding light on this dynamic duo, making data serialization a seamless experience for developers working with REST APIs."
    Investment banking as a career in India

    ReplyDelete