Base solution for your next web application
Open Closed

Have blanks instead of null in AppService returned JSON #8794


User avatar
0
daws created

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)
  • User Avatar
    0
    ismcagdas created
    Support Team

    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 ?

  • User Avatar
    0
    daws created

    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 ?

  • User Avatar
    0
    ismcagdas created
    Support Team

    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.

  • User Avatar
    0
    daws created

    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

  • User Avatar
    1
    ismcagdas created
    Support Team

    @daws

    Thank you for sharing steps of your solution.