0

I am trying to serialize any type in JS to object in C#, and nothing seems to work.

I have a property on my EventAction

public DotNetObjectReference<EventAction<T>> DotNetObjRef { get; }

which is used to call an event from JS code. An example would be:

function onCellValueChanged(data, handler) {

    var mapped = {
        columnName: data.column.colId // string
        rowIndex: data.rowIndex, // number
        oldValue: data.oldValue, // any
        newValue: data.newValue, // any
    };

    handler.dotNetObjRef.invokeMethodAsync('Invoke', mapped);
}

The calling method part works fine. The serialization is only partially done. In above example, I have a class called

public class CellValueChangedArgs
{
    public string ColumnName { get; set; } = string.Empty;
    public int RowIndex { get; set; }
    public object? OldValue { get; set; }
    public object? NewValue { get; set; }
}

and when instance of this class is called, string and int properties are serialized properly, object? types are not (they contain JsonElement instance instead of actual value, which can be string, number, datetime...).

If I change NewValue and OldValue types to string, then it works.

Anyone has any idea why? Is it a proper way to serialize it to string, and then dial with the conversion manually?

1
  • User string instead of object?, it works fine. Commented Jun 1, 2023 at 11:44

1 Answer 1

1

Ask yourself this, how do you deserialize to something when you do not know what it is?

When the property with type object is serialized, the type is known and can be done. But deserialization is a completely different story and is impossible unless you can define the type.

I suggest adding your expected type by either using generics or passing the type to and from JavaScript.

Perhaps use this

public class CellValueChangedArgs
{
    public string ColumnName { get; set; } = string.Empty;
    public int RowIndex { get; set; }
    public string? OldValue { get; set; }
    public string? NewValue { get; set; }
}

And cast your strings to your expected value type using Reflection and TryParse methods.

Sign up to request clarification or add additional context in comments.

1 Comment

"Ask yourself this...". I may not know, but runtime does? For example, if JS oldValue is of type any, and it contains number, typeof(oldValue) returns number. So, JS Interop serialization could cast this to C# double variable, and then assign it to C# object property. If I use custom JsonConverter<object>, and inspect JsonTokenType, I can do this manually. It is strange to me, however, that this is not built in, since any property is quite frequent in JS.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.