Skip to content

System.Text.Json failes to serialize System.Net.IPNetwork and System.Net.IPAddress objects #118725

@64J0

Description

@64J0

Description

I was trying to serialize a System.Net.IPNetwork and was consistently getting some exceptions. After debugging a bit more, I found out that the problem is inside System.Text.Json itself.

This erros happens for System.Net.IPAddress objects too.

Reproduction Steps

Check this snipped from F#:

System.Net.IPNetwork.Parse("127.0.0.1/32")
|> System.Text.Json.JsonSerializer.SerializeToUtf8Bytes

You can run it using the FSI.

The result I'm getting:

Image

Expected behavior

Correctly serialize the System.Net.IPNetwork and System.Net.IPAddress objects.

Actual behavior

Throws this exception:

System.Net.Sockets.SocketException (95): Operation not supported
   at System.Net.IPAddress.ThrowSocketOperationNotSupported()
   at System.Net.IPAddress.get_ScopeId()
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo`1.GetMemberAndWriteJson(Object obj, WriteStack& state, Utf8JsonWriter writer)
   at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.Metadata.JsonTypeInfo`1.Serialize(Utf8JsonWriter writer, T& rootValue, Object rootValueBoxed)
   at System.Text.Json.JsonSerializer.WriteBytes[TValue](TValue& value, JsonTypeInfo`1 jsonTypeInfo)
   at System.Text.Json.JsonSerializer.SerializeToUtf8Bytes[TValue](TValue value, JsonSerializerOptions options)

Regression?

No response

Known Workarounds

Transforming this IPNetwork, or System.Net.IPAddress objects into strings works.

Configuration

  • .NET SDK 9.0.101
  • Ubuntu 24.04
  • x86

Other information

I'd check the exception stack information.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions