custom_marshaller

package
v0.1.82 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 19, 2025 License: AGPL-3.0 Imports: 3 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CustomMarshaller

type CustomMarshaller struct {
	// contains filtered or unexported fields
}

CustomMarshaller is an auxiliary struct that helps to change the behavior of the default MarshalJSON method for specific types allowing custom marshalling of the fields

func New

func New(i any) CustomMarshaller

func (CustomMarshaller) MarshalJSON

func (instance CustomMarshaller) MarshalJSON() ([]byte, error)

MarshalJSON iterates over all the fields of the struct allowing custom marshalling of the fields - [32]byte will be marshalled as a common.Hash - [20]byte will be marshalled as a common.Address - []byte will be marshalled as a common.Hash - If the field is a struct or a pointer to a struct, it will be marshalled recursively - All the rest of the fields will be marshalled as is

Example:

type MyStruct struct {
	Field1 string
	Field2 [32]byte
	Field3 [20]byte
	Field4 []byte
}
myStruct := MyStruct{
	Field1: "value",
	Field2: [32]byte{},
	Field3: [20]byte{},
	Field4: []byte{},
}

result, _ := json.Marshal(myStruct)
fmt.Println(string(result))

Result returned when marshalling MyStruct directly:

{
	"Field1": "value",
	"Field2": [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
	"Field3": [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
	"Field4": [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
}

result, _ = json.Marshal(custom_marshaller.New(myStruct))
fmt.Println(string(result))

Result returned when marshalling MyStruct using CustomMarshaller:

{
	"Field1": "value",
	"Field2": "0x0000000000000000000000000000000000000000000000000000000000000000",
	"Field3": "0x0000000000000000000000000000000000000000",
	"Field4": "0x0000000000000000000000000000000000000000000000000000000000000000"
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL