简体   繁体   中英

Change Blazor JS interop Serializer Settings

I am looking to see how to set the json serializor converter settings when you call _jsRuntime.InvokeAsync method. The method it self doesn't take in any json serialization settings. I believe you would need to set the settings for the project. So far I have not been able to find a way to achieve that.


My Converter:

public class VectorConverter : JsonConverter<System.Numerics.Vector3>
{
    public override System.Numerics.Vector3 Read(ref Utf8JsonReader reader, 
        Type typeToConvert, JsonSerializerOptions options) 
    {
        if(reader.TokenType != JsonTokenType.StartObject)
        {
            throw new JsonException();
        }
        
        System.Numerics.Vector3 result = new System.Numerics.Vector3();
    
        while (reader.Read())
        {
            if(reader.TokenType == JsonTokenType.EndObject)
            {
                return result;
            }
            
            if(reader.TokenType != JsonTokenType.PropertyName)                
            {
                throw new JsonException();
            }
            
            switch(reader.GetString())
            {
                case "x":
                    result.X = (float)reader.GetDouble();
                    break;
    
                case "y":
                    result.Y = (float)reader.GetDouble();
                    break;
                
                case "z":
                    result.Z = (float)reader.GetDouble();
                    break;
            }
        }
    
        throw new JsonException();
    }
    
    public override void Write(Utf8JsonWriter writer, 
        System.Numerics.Vector3 value, JsonSerializerOptions options)
    {    
        writer.WriteNumber("x", value.X);
        writer.WriteNumber("y", value.Y);
        writer.WriteNumber("z", value.Z);
    }
}

As of writing, it seems it is unfortunately not possible (and STILL not possible) to modify the JSON serializer configuration in a Blazor app. The JsonSerializerOptions instance configured for the JSRuntime abstract base class is internal, and getter-only. So no way for us to modify the Converters collection. It's not even virtual, so you won't be able to subclass JSRuntime itself.

Relevant source here.

Also worth mentioning it's not using the static Default instance either, which is by the way also not possible to be configured because in the app's entry point it seems it's already been used (and there is a check in place to not modify it once used). It wouldn't matter much though, as JSRuntime doesn't use this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM