Overriding default servicestack serializer  Topic is solved

Discussions relating to plugin development, and the Jiwa API.

Overriding default servicestack serializer

Postby iamgurney » Tue May 30, 2023 7:26 am

Hello everyone,

I am new to this forum and I am also creating my first plugin with custom API endpoints. I am using a library that contains over 100 classes with models using the Newtonsoft.Json serializer and the JsonProperty attribute. The problem I'm facing is that the class library uses the Newtonsoft.Json serializer, while Jiwa has the default ServiceStack serializer. Our class library uses snake case for JSON, while the class models use Pascal case (the default case in .NET). As a result, when accessing our endpoints, we are getting null values for all properties, except for properties that consist of a single word.

Code: Select all
public void Configure(Plugin Plugin, ServiceStackHost AppHost, Funq.Container Container, Manager JiwaApplicationManager)
    {
        JsConfig<object>.SerializeFn = Newtonsoft.Json.JsonConvert.SerializeObject;
        JsConfig<object>.DeSerializeFn = Newtonsoft.Json.JsonConvert.DeserializeObject;
    }


the above code is not working for us. Need help! Iwant to override the ServiceStack serializer with the Newtonsoft serializer.
iamgurney
I'm new here
I'm new here
 
Posts: 6
Joined: Tue May 30, 2023 7:15 am

Re: Overriding default servicestack serializer

Postby SBarnes » Tue May 30, 2023 9:34 am

You actually need to do something like the below, where in my case I was changing dates to utc but that is only half the battle as you also have to cater for dealing with anything that comes out of an auto query to do that see this link https://docs.servicestack.net/ormlite/type-converters.


Code: Select all
ServiceStack.Text.JsConfig<DateTime>.SerializeFn = input =>   {
                                                         System.Diagnostics.Debugger.Launch();
                                                         if (input.Kind == DateTimeKind.Utc)
                                                         {
                                                            return input.ToString();
                                                         }
                                                         TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("AUS Eastern Standard Time");
                                                         DateTime dtOut = TimeZoneInfo.ConvertTimeToUtc(input, timeZoneInfo);
                                                         return dtOut.ToString();
                                                         
         };



You could also try setting ServiceStack.Text.JsConfig.EmitCamelCaseNames = false
Regards
Stuart Barnes
SBarnes
Shihan
Shihan
 
Posts: 1619
Joined: Fri Aug 15, 2008 3:27 pm
Topics Solved: 175

Re: Overriding default servicestack serializer

Postby Mike.Sheen » Tue May 30, 2023 12:00 pm

Hi Symimake,

If you just want snake case, I think you can just pass the jsconfig value in the request url, so no need for a custom plugin to mess with the serialisation behaviours.

For example, without any jsconfig directives the json looks like this:

https://api.jiwa.com.au/Queries/DB_Tran ... ormat=json

Code: Select all
{"Results":[{"Ref":"YYDW1997","TranDate":"2023-02-13T09:14:41.0000000","InvRemitNo":"100485-D01","Amount":3685.000000,"AllocatedAmount":0.000000,"GSTAmount":335.000000}],"Meta":{}}


And with EmitLowercaseUnderscoreNames

https://api.jiwa.com.au/Queries/DB_Tran ... aultValues

Code: Select all
{"results":[{"ref":"YYDW1997","tran_date":"2023-02-13T09:14:41.0000000","inv_remit_no":"100485-D01","amount":3685.000000,"allocated_amount":0.000000,"gst_amount":335.000000}],"meta":{}}


See if that works for you.

There are more customisation options available via just url parameters, see customize json responses in service.

If you don't want to have to provide the query parameter in the URL, attached is a plugin which will set the JsConfig setting for you instead.
Plugin REST API Snake Case.xml
(9.58 KiB) Downloaded 65 times


And as Stuart indicated, you can also have complete control over the serialisation by a plugin setting the SerializeFn property in the JsConfig static class. You can copy paste Stuarts example code snippet into the Configure method of the plugin I provided, and alter the method code to do anything you want - including creating a Newtonsoft serialiser and outputting that, so then you'll know what is output is compatible with what you need.
Mike Sheen
Chief Software Engineer
Jiwa Financials

If I do answer your question to your satisfaction, please mark it as the post solving the topic so others with the same issue can readily identify the solution
User avatar
Mike.Sheen
Overflow Error
Overflow Error
 
Posts: 2444
Joined: Tue Feb 12, 2008 11:12 am
Location: Perth, Republic of Western Australia
Topics Solved: 756

Re: Overriding default servicestack serializer

Postby SBarnes » Tue May 30, 2023 12:18 pm

Regards
Stuart Barnes
SBarnes
Shihan
Shihan
 
Posts: 1619
Joined: Fri Aug 15, 2008 3:27 pm
Topics Solved: 175

Re: Overriding default servicestack serializer

Postby iamgurney » Tue May 30, 2023 5:46 pm

I followed different methods from servicestack documentation but the version in jiwa is 5.0.0.0. The current documentation is not applicable for this version.


Code: Select all
AppHost.ContentTypes.Register(MimeTypes.Json,
        (IRequest req, object dto, Stream stream) =>
        {
            using (var writer = new StreamWriter(stream, new UTF8Encoding(false), 4096, true))
            {
                var json = JsonConvert.SerializeObject(dto);
                writer.Write(json);
            }
        },
        (Type type, Stream stream) =>
        {
            using (var reader = new StreamReader(stream, new UTF8Encoding(false), true, 4096, true))
            {
                var json = reader.ReadToEnd();
                return JsonConvert.DeserializeObject(json, type);
            }
        });


Tried this SBarnes from the link you provided but after that I am getting 400 bad request on endpoint response. Regarding your first comment do I need to define converter for all classes ?


Consider the example model

Code: Select all
public class WarehouseModel{
        [JsonProperty("warehouse_id")]
        public int? WarehouseId { get; set; }


        [JsonProperty("created_via")]
        public string CreatedVia { get; set; }

        [JsonProperty("warehouse_name")]
        public string WarehouseName { get; set; }

        [JsonProperty("main_contact")]
        public string MainContact { get; set; }

}



Mike, the sample code you provided is also not working
iamgurney
I'm new here
I'm new here
 
Posts: 6
Joined: Tue May 30, 2023 7:15 am

Re: Overriding default servicestack serializer

Postby Mike.Sheen » Tue May 30, 2023 5:52 pm

iamgurney wrote:Mike, the sample code you provided is also not working


I tested that and confirmed it works before I posted it. It might be the version of Jiwa you are using which you have not disclosed. The version I tested against is Jiwa 7.2.1 SR16, with the REST API plugin version included in the JiwaAPI.zip.

Also you need to define what you mean by "not working" - are you getting errors? If not, then you probably just didn't restart your API after importing the plugin.

Also did you try just using the url parameter? Click the second ink I posted which contains the url parameter jsconfig=EmitLowercaseUnderscoreNames - it outputs snake case JSON - is that not what you asked for?
Mike Sheen
Chief Software Engineer
Jiwa Financials

If I do answer your question to your satisfaction, please mark it as the post solving the topic so others with the same issue can readily identify the solution
User avatar
Mike.Sheen
Overflow Error
Overflow Error
 
Posts: 2444
Joined: Tue Feb 12, 2008 11:12 am
Location: Perth, Republic of Western Australia
Topics Solved: 756

Re: Overriding default servicestack serializer

Postby iamgurney » Tue May 30, 2023 5:59 pm

Mike.Sheen wrote:Also you need to define what you mean by "not working" - are you getting errors? If not, then you probably just didn't restart your API after importing the plugin.


after adding the line
Code: Select all
ServiceStack.Text.JsConfig.EmitLowercaseUnderscoreNames = true;


I am getting this error
Code: Select all
"error_code": "FileLoadException",
        "message": "Could not load file or assembly 'Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)",
iamgurney
I'm new here
I'm new here
 
Posts: 6
Joined: Tue May 30, 2023 7:15 am

Re: Overriding default servicestack serializer

Postby Mike.Sheen » Tue May 30, 2023 6:02 pm

iamgurney wrote:I am getting this error
Code: Select all
"error_code": "FileLoadException",
        "message": "Could not load file or assembly 'Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)",


Not from the plugin I provided you with you aren't - my plugin has no reference to Newtonsoft.

That's some mess you've created, try with just my plugin and don't modify it.
Mike Sheen
Chief Software Engineer
Jiwa Financials

If I do answer your question to your satisfaction, please mark it as the post solving the topic so others with the same issue can readily identify the solution
User avatar
Mike.Sheen
Overflow Error
Overflow Error
 
Posts: 2444
Joined: Tue Feb 12, 2008 11:12 am
Location: Perth, Republic of Western Australia
Topics Solved: 756

Re: Overriding default servicestack serializer

Postby iamgurney » Tue May 30, 2023 6:07 pm

Mike.Sheen wrote:Not from the plugin I provided you with you aren't - my plugin has no reference to Newtonsoft.

That's some mess you've created, try with just my plugin and don't modify it.


Yes you are right. As I said my all models have JsonProperty Attribute and also some other filters. I can't modify the class library because I am using it an another asp.net application. The only solution I am expecting is to override ServiceStack default serializer with Newtonsoft.

Edit: I put Newtonsoft and the class library in the plugin embedded references
iamgurney
I'm new here
I'm new here
 
Posts: 6
Joined: Tue May 30, 2023 7:15 am

Re: Overriding default servicestack serializer

Postby Mike.Sheen » Tue May 30, 2023 6:17 pm

iamgurney wrote:The only solution I am expecting is to override ServiceStack default serializer with Newtonsoft.


I suggest you ask the ServiceStack authors on how to change their serialiser to be Newtonsoft.
Mike Sheen
Chief Software Engineer
Jiwa Financials

If I do answer your question to your satisfaction, please mark it as the post solving the topic so others with the same issue can readily identify the solution
User avatar
Mike.Sheen
Overflow Error
Overflow Error
 
Posts: 2444
Joined: Tue Feb 12, 2008 11:12 am
Location: Perth, Republic of Western Australia
Topics Solved: 756

Next

Return to Technical and or Programming

Who is online

Users browsing this forum: No registered users and 20 guests

cron