Preserve casing in Blazor JSInterop?

Viewed 660

I have these data structures that I'm sending between an ASP.NET Core server and Javascript. The data is sent as JSON serialized using websocket messages.

In this example the object has a parameter with the name Text (Uppercase T)

Server(C# object) --> System.Text...JsonSerialize --> WebSocket --> JSON.parse --> JS object

Final JS object:

{
  "Text": "Hello"
}

After introducing Blazor WebAssembly which talks directly to the server using ClientWebSocket

Server(C# object) --> System.Text...Serialize --> WebSocket --> System.Text...Deserialize --> C# object

The problem, and my question comes with JSInterop.

Blazor --> JSInterop --> JavaScript

Final JS object:

{
  "text": "Hello"
}

Now the Text property has a name text all in lowercase.

How can I configure the object serialization to preserve the casing from the C# objects?

Workaround

Current workaround would be to serialize the object before passing it via JSInterop and then run JSON.parse to get back the objects.

C#

var jsonString = JsonSerializer.Serialize(arg)
JSRuntime.InvokeVoidAsync("MyFunction", jsonString);

JavaScript

window.MyFunction = function (jsonString) {
    var arg = JSON.parse(jsonString)
    ....
}
1 Answers

you can use [JsonPropertyName("PropName")] on each property, something like this:

public class ClientObj
{
    [JsonPropertyName("MyProp")]
    public int MyProp { get; set; }
}

this stops it atm from giving camelCase properties in js.

the reason this is happening: https://github.com/aspnet/Mvc/issues/4283

Related