I have an AppService method which returns a very large array of int? (nullable int).
Most values in this array are null.
Currently, when calling the method via Web api, the response array is formatted like this in JSON :
[null,null,null, ..., 3, 4, 8, 11, 12, null, null, null, ...]
In order to spare network bandwith, I want my array to be like this :
[,,, ..., 3, 4, 8, 11, 12,,,, ...]
Is it doable without bypassing the service-proxies JSON parsing functions ?
(Using Aspnetcore 7.2.3 with angular)
5 Answer(s)
-
0
Hi @daws,
I'm not sure if it is possible on the client side at the moment but as you know service-proxies are auto generated. Maybe you can use Angular's httpClient service for such special cases and handle it manually on the client side. What do you think ?
-
0
I think that since this JSON response is returned by the AppService, it should be handled first on the server side, shouldn't it ?
Where does the AppService format the returned object to JSON ?
-
0
Hi @daws,
AppServices are converted to ASP.NET Controllers, so they use same formatters as Controllers. You can write a custom ContractResolver and use it for a specific app service.
-
0
My solution is to change the AppService method signature to return a JSON string. I then transform and parse that string when received in the frontend.
In order to make it work, I had to do the following :
- In the backend :
- Use a DefaultContractServiceResolver with a camelcaseNamingStrategy
- Write a custom JSON converter which replaces all nulls by an empty string
- In the object class, assign the JSON converter to the array property with a data annotation
- In the frontend :
- Parse the received string to JSON using a reviver function
- In the reviver function, filter the property which has the null array, and replace the blanks with nulls using a Regex
- I then get an object, but its array property has been parsed as a string because it was not yet a valid JSON array
- Parse that property to JSON (it will now correctly parse it)
This is tedious and it breaks the webAPI contract but I haven't found a better solution to optimize the size of the transferred JSON. If someone comes up with a better solution, please share.
Thanks
- In the backend :
-
1
@daws
Thank you for sharing steps of your solution.