Skip to content

Add opt-in support for json.Marshaler and json.Unmarshaler via transcoding #677

@fxamacker

Description

@fxamacker

This was proposed by @benluddy, approved, and he already opened PR #673 for this:

Recognition of types implementing these interfaces is important for users requiring drop-in compatibility with encoding/json. Without it, if a type implements the JSON interfaces without also implementing the corresponding CBOR interfaces, its JSON and CBOR representations can have substantial structural differences.

Consider what can happen with a type like https://pkg.go.dev/k8s.io/apimachinery/pkg/util/intstr#IntOrString if it were to only implement json.Marshaler and json.Unmarshaler (and not cbor.Marshaler or cbor.Unmarshaler):

  1. ToJSON(IntOrString{Type: String, StrVal: "a"}) => "a"
  2. FromJSON[any]("a") => string("a")
  3. ToCBOR(string("a")) => 0x6161
  4. FromCBOR[IntOrString](0x6161) => **error: can't unmarshal CBOR text string number to struct**

With automatic transcoding, we can preserve the faithful roundtrip:

  1. FromCBOR[IntOrString](0x6161) => FromJSON[IntOrString](CBORToJSON(0x6161)) => FromJSON[IntOrString]("a") => IntOrString{Type: String, StrVal: "a"}

This feature is not enabled by default, so it won't unintentionally change behavior of existing user applications.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions